Sring 中有一个 Aware 接口,并且有许多子接口继承于它。
如其名字一样,实现这种接口的 Bean,能自身感知到容器的存在,容器在操作 Bean 的过程中,会调用感知接口中的方法。Spring 设计的这些接口,等于埋下了很多钩子函数,让开发者能在某些关键节点上,运行自定义的代码。
很多感知接口都和 Spring 生命周期有关,会在整个生命周期中触发运行,比如 BeanNameAware、ApplicationContextAware 等。
比如如下几个接口,通过这些接口的名字,也能猜出这些感知接口的含义和用途。
ApplicationContextAware,可以让 Bean 感知到 Spring 容器对象,获得容器 ApplicationContext 引用。
BeanFactoryAware,可以让 Bean 感知到 BeanFactory 对象,获得 BeanFactory 的引用。
BeanNameAware,让 Bean 获取自己在 BeanFactory 配置中的名字(根据情况是 id 或者 name)。
一个 User 类,实现如下的感知接口:
@Component
public class User implements ApplicationContextAware, BeanFactoryAware,
BeanNameAware {
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
System.out.println("setApplicationContext called");
System.out.println("setApplicationContext:: Bean Definition Names=" +
Arrays.toString(applicationContext.getBeanDefinitionNames()));
}
public void setBeanFactory(BeanFactory beanFactory)
throws BeansException {
System.out.println("setBeanFactory called");
System.out.println("setBeanFactory:: user bean singleton=" +
beanFactory.isSingleton("user"));
}
public void setBeanName(String name) {
System.out.println("setBeanName called");
System.out.println("setBeanName:: Bean Name defined in context=" +
name);
}
}
配置 ComponentScan 路径
@ComponentScan(value="com.learn")
public class Config {
}
Main 方法运行:
public static void main(String[] args) {
//使用Config.class这个配置类
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
applicationContext.close();
}
main 运行的时候,容器会从配置的扫描路径中扫描到 User 这个类,并且将这个类的实例注入到容器中,此时就会触发感知接口中的各个方法。运行结果如下:
setBeanName called setBeanName:: Bean Name defined in context=user setBeanFactory called setBeanFactory:: user bean singleton=true setApplicationContext called setApplicationContext:: Bean Definition Names=[org.springframework.context.annotation.internalConfigurationAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.annotation.internalRequiredAnnotationProcessor, org.springframework.context.annotation.internalCommonAnnotationProcessor, org.springframework.context.event.internalEventListenerProcessor, org.springframework.context.event.internalEventListenerFactory, config, org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor, org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor, user]