参考:官方文档
1 Aware接口
Aware
的本意是感知。当bean
实现了对应的Aware
接口,BeanFactory
就会在产生这个bean
的时候根据对应的Aware
接口,给这个bean
注入相应的属性,这样bean
就能够获取外界资源的引用了。
1.1 ApplicationContextAware 和 BeanNameAware
1.1.1 ApplicationContextAware接口
当一个bean
实现了org.springframework.context.ApplicationContextAware
接口,那么这个实力bean
就会被注入ApplicationContext
对象,下面是这个接口的定义:
public interface ApplicationContextAware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
使用它的一个例子:
@Component
public class BeanA implements ApplicationContextAware {
private ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = applicationContext;
}
// ...
}
从Spring 2.5
开始,可以通过@Autowired
自动注入ApplicationContext
对象:
@Component
public class BeanA {
@Autowired
private ApplicationContext applicationContext;
// ...
}
1.1.2 BeanNameAware接口
在bean
的内部,它是不知道容器给自己取的id
是什么。当一个bean
实现了org.springframework.beans.factory.BeanNameAware
接口,就可以在创建这个bean
的时候将id
注入进来。下面是该接口的定义:
public interface BeanNameAware {
void setBeanName(String name) throws BeansException;
}
这些回调是在属性填充完毕之后,在初始化回调之前调用。
1.2 其它的Aware接口
Spring
还提供了一些很重要的Aware
接口,这些接口的命名规则就是根据需要依赖的属性来命名的:
接口 | 注入的属性 | Explained in… |
---|---|---|
ApplicationContextAware | Declaring ApplicationContext . | ApplicationContextAware and BeanNameAware |
ApplicationEventPublisherAware | Event publisher of the enclosing ApplicationContext . | Additional Capabilities of the ApplicationContext |
BeanClassLoaderAware | Class loader used to load the bean classes. | Instantiating Beans |
BeanFactoryAware | Declaring BeanFactory . | ApplicationContextAware and BeanNameAware |
BeanNameAware | Name of the declaring bean. | ApplicationContextAware and BeanNameAware |
BootstrapContextAware | Resource adapter BootstrapContext the container runs in. Typically available only in JCA aware ApplicationContext instances. | JCA CCI |
LoadTimeWeaverAware | Defined weaver for processing class definition at load time. | Load-time Weaving with AspectJ in the Spring Framework |
MessageSourceAware | Configured strategy for resolving messages (with support for parametrization and internationalization). | Additional Capabilities of the ApplicationContext |
NotificationPublisherAware | Spring JMX notification publisher. | Notifications |
ResourceLoaderAware | Configured loader for low-level access to resources. | Resources |
ServletConfigAware | Current ServletConfig the container runs in. Valid only in a web-aware Spring ApplicationContext . | Spring MVC |
ServletContextAware | Current ServletContext the container runs in. Valid only in a web-aware Spring ApplicationContext . | Spring MVC |