前言
在Spring中有一个及其底层且名字很熟悉的接口Aware,如常见的BeanNameAware、ApplicationContextAware等。如果在做底层框架开发时,这个接口大概率会被用到。
Aware作用
源码中的注释
A marker superinterface indicating that a bean is eligible to be notified by the Spring container of a particular framework object through a callback-style method. The actual method signature is determined by individual subinterfaces but should typically consist of just one void-returning method that accepts a single argument.
Note that merely implementing Aware provides no default functionality. Rather, processing must be done explicitly, for example in a org.springframework.beans.factory.config.BeanPostProcessor. Refer to org.springframework.context.support.ApplicationContextAwareProcessor for an example of processing specific *Aware interface callbacks.
大概意思是 这是 一个标记超接口 , 指示bean有资格通过一个回调样式的方法得到Spring容器对特定框架对象的通知。实际的方法签名由各个子接口决定,但通常应该只包含一个接受单个参数的返回void的方法。
通俗的讲,就是实现Aware接口,可以访问到Spring容器。
案例
如常见的BeanNameAware, 在创建此 bean 的 bean 工厂中设置 bean 的名称,在填充普通 bean 属性之后但在初始化回调之前调用。因此如果一个bean想直接获取当前对象在Spring容器中的名字时,可以实现BeanNameAware接口,并且实现它的回调方法 setBeanName 即可得到bean名称。
package com.my.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author lishuzhen
* @createTime 2022年01月28日 22:29:00
*/
public class TestRun {
public static void main(String[] args) {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/spring/applicationContext.xml");
TestAware2 bean = ac.getBean(TestAware2.class);
}
}
package com.my.test;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.stereotype.Component;
/**
* @author lishuzhen
* @createTime 2022年01月28日 22:26:00
*/
@Component
public class TestAware2 implements BeanNameAware {
private String beanName;
@Override
public void setBeanName(String name) {
this.beanName = name;
System.out.println("beanName is " + name);
}
}
源码分析
SpringBean创建过程(部分):
// Initialize the bean instance.
Object exposedObject = bean;
try {
// 填充属性
populateBean(beanName, mbd, instanceWrapper);
// 初始化bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
初始化bean方法中调用 Aware的回调方法,如 BeanNameAware的serBeanName等等。
private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}