背景
Spring 容器的IOC最大优势就是我们的应用程序对容器是无感的,保持绝对的耦合,唯一的关联点就是注解。 但是我们在开发应用程序的时候又不可避免的需要用到Spring容器的所提供的资源,这时候Application就必须能够意识到Spring容器提供的各个机制的存在,这就是Spring Aware。使用了Aware之后,Application就和Spring耦合了,但是我觉得这也不是什么问题,应为Spring现在已经是Java里面的基础设施了。
Spring提供的一些Aware接口
接口名 | 作用 |
---|---|
ApplicationContextAware | 获得当前application context,这样可以调用容器的服务 |
BeanFactoryAware | 获得当前的Beanfactory,就可以调用容器的服务 |
MessageSourceAware | MessageSourceAware |
BeanNameAware | 获得到容器中Bean的名称 |
ResourceLoaderAware | 获得资源加载器,可以获得外部资源文件 |
ApplicationEventPublisherAware | 应用事件发布器,可以发布事件 |
Spring Aware的目的是为了让Bean获得Spring容器的服务。因为ApplicationContext接口集成了MessageSource接口,ApplicationEventPublisherAware接口和ResourceLoaderAware接口,所以Bean继承ApplicationContextAware可以获得Spring容器的所有服务,但原则上我们还是用到什么接口就实现什么接口。
Spring Aware运行示例
实现BeanNameAware, ResourceLoaderAware 接口
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware{
private String beanName;
private ResourceLoader loader;
public void outputResult(){
System.out.println("Bean的名称为:" + beanName);
Resource resource =
loader.getResource("classpath:text.properties");
try{
System.out.println("ResourceLoader加载的文件内容为: " + IOUtils.toString(resource.getInputStream()));
}catch(IOException e){
e.printStackTrace();
}
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.loader = resourceLoader;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
}
基于注解的配置类
@Configuration
@ComponentScan("com.example.demo.test.aware")
public class AwareConfig {
}
Application
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
AwareService awareService = context.getBean(AwareService.class);
awareService.outputResult();
context.close();
}
}
运行结果