搞懂xxxAware家族对理解Spring源码和提高代码能力也有帮助。
Spring中常见xxxAware接口列举如下:
- ApplicationContextAware
- BeanNameAware
- EmbeddedValueResolverAware
- EnvironmentAware
- MessageSourceAware
- ResourceLoaderAware
1、ApplicationContextAware
ApplicationContextAware的作用就是通过它,spring可以把上下文环境对象ApplicationContext注入进来,然后通过ApplicationContext对象来得到Spring容器中的bean,做一些应用级别的事情。
简而言之:ApplicationContextAware是用来获取ApplicationContext对象的。
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* 类说明:演示使用 ApplicationContextAware 获取配置文件的属性
*/
@PropertySource(value = "classpath:/test.properties")
@Component
public class Plane implements ApplicationContextAware {
private ApplicationContext applicationContext;
public Plane() {
System.out.println("Plane.......constructor");
}
@PostConstruct
public void init() {
System.out.println("Plane.......init........@PostConstruct");
Environment environment = applicationContext.getEnvironment();
String property = environment.getProperty("bird.color");
System.out.println("Plane...... bird.color=" + property);
}
@PreDestroy
public void destroy() {
System.out.println("Plane......destroy........@PreDestroy");
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
// 容器初始化,将applicationContext传进来,那么其他方法就可使用到IOC容器了
// 这个方法是ApplicationContextAwareProcessor的
this.applicationContext = context;
}
}
写测试类 验证一下:
package org.xiaobuisme.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.xiaobuisme.example.cap8.Plane;
public class Cap8Test {
public static void main(String[] args) {
// 验证 实现 ApplicationContextAware的接口后,如何使用 applicationContext获取配置文件变量
AnnotationConfigApplicationContext anno = new AnnotationConfigApplicationContext(Plane.class);
// 打印出 Plane...... bird.color=blue
// 说明 此种方式 可以使用applicationContext进行操作
anno.close();
}
}
输出结果:
Plane.......constructor
Plane.......init........@PostConstruct
Plane...... bird.color=blue
九月 08, 2023 11:12:55 上午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@5fa7e7ff: startup date [Fri Sep 08 11:12:55 CST 2023]; root of context hierarchy
Plane......destroy........@PreDestroy
2、BeanNameAware
用来获取当前bean的名称的
3、EmbeddedValueResolverAware
用来解析表达式的
4、EnvironmentAware
用来获取环境变量的
5、MessageSourceAware
用来做国际化的
6、ResourceLoaderAware
用来加载资源文件的