自动装配 04 Aware 注入Spring底层组件 & 原理
总接口:
Aware
- 自定义组件想要使用Spring容器底层的一些组件(ApplicationContext BeanFactory 等等)
- 需要让自定义组件实现xxAware接口:在创建对象的时候会调用接口规定的方法注入相关组件 总体参照
Aware
接口 ,把Spring底层一些组件注入到自定义的bean中 - xxxAware功能:使用xxProcessor 如ApplicationContextAware ==》 ApplicationContextAwareProcessor,利用后置处理器判断实现了哪个接口,就将Bean转成相应的接口类型,再选择注入相应类型的applicationContext
/**
* 生命周期 感知接口测试
*/
@Component//注入后自动调用实现的感知接口方法
public class Red implements ApplicationContextAware, BeanNameAware, EmbeddedValueResolverAware {
private ApplicationContext applicationContext;
@Override
public void setBeanName(String name) {
System.out.println("调用了 setBeanName");
System.out.println("当前bean的名字 " + name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
System.out.println("调用了 setApplicationContext");
}
/**
* 解析占位符
* @param resolver
*/
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
System.out.println("调用了 setEmbeddedValueResolver");
String resolveString = resolver.resolveStringValue(" hello ${os.name} ; age #{22-1}");
System.out.println("解析的字符串 " + resolveString);
}
}
配置类
@Configuration
@ComponentScan(value = {"com.example.annotations.service","com.example.annotations.dao","com.example.annotations.controller","com.example.annotations.bean"})
public class MainConfig4Autowire {
}
测试
@Test
void autowiredTest(){
//配置类测试
System.out.println("准备创建容器");
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig4Autowire.class);
System.out.println("容器创建完毕");
//关闭容器
applicationContext.close();
System.out.println("容器已关闭");
}
测试结果: