Spring中有很多Aware接口,它们的具体作用是什么呢?实现这些Aware接口的bean在初始化后,可以获得对应的Spring资源,利用对应的资源对Spring做扩展。
常见的Aware:
- ApplicationContextAware:向实现了这个接口的bean提供ApplicationContext(IOC容器的上下文信息),实现了这个接口的bean必须配置到Spring的bean配置文件中去,并且由Spring的bean容器去加载。
- BeanNameAware:提供一个关于BeanName的定义的内容。
- ApplicationEventPublisherAware:事件的发布
- BeanClassLoaderAware:找到相关的类加载器
以ApplicationContextAware为例:
public class TestApplicationContextAware implements ApplicationContextAware{ private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { TestApplicationContextAware testApplicationContextAware = this.applicationContext.getBean(TestApplicationContextAware.class); System.out.println(testApplicationContextAware.hashCode()); } }