Aware英文意思是“感知”,在spring中其实是感知spring容器中自身的一些属性;
在IOC中介绍了BeanPostProcessor后置处理器,被bean后置处理器拦截的bean对象,只有实现了指定的Aware接口,才可以在初始化过程中得到Spring框架提供内部的资源.
下面简单介绍Aware几个继承接口类例子
1.BeanNameAware
实现了当前接口的类的【bean对象在初始化时】得到bean对象在Spring容器对应的name
/**
**实现BeanNameAware接口得到bean对象在容器中的名称
*/
@Component
public class Test implements BeanNameAware{
public void setBeanName(String name) {
//获取到bean名称
System.out.println("类的bean对象name为 "+name);
}
}
2.EmbeddedValueResolverAware
实现了当前接口的类的bean对象在初始化时【字符串解析器】对SPEL以及属性内容表达式
进行解析
1).属性文件config.properties
my.name=小明
2).spring配置类
@PropertySource("classpath:/config.properties")//加载属性文件
@ComponentScan(value={"com.test.beans"})
@Configuration
public class ApplicationConfig {
}
3)bean类
@Component
public class Test implements EmbeddedValueResolverAware{
public void setEmbeddedValueResolver(StringValueResolver resolver) {
String value = resolver.resolveStringValue("我叫${my.name.name},我今年#{2021-1990}");
System.out.println("value = "+value);
}
}
4).测试类
public class TestMain {
public static void main(String[] args) {
// 1.获得Spring容器对象
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ApplicationConfig.class);
Test obj =context.getBean(Test.class);
context.close();
System.out.println(obj);
}
}
3.ApplicatoinContextAware接口
实现了当前接口的类的【bean对象在初始化时】得到Spring的IOC容器
/**
**实现ApplicationContextAware接口得到ApplicationContext容器对象
*/
@Component
public class Test implements ApplicationContextAware{
private ApplicationContext context;//得到管理它的Spring容器;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Override
public String toString() {
//输出容器
return "Bird [context=" + context + "]";
}
}