Spring Aware
Spring 的依赖注入的最大亮点就是你所有的 Bean 对 Spring 容器的存在都是无意识的.即你可以将你的容器替换成别的容器.
但是在实际的项目中,你不可避免要用到 Spring 容器本身的功能资源,这是你的 Bean 必需要意识到 Spring 容器的存在,才能调用 Spring 所提供的资源,这就是所谓的 Spring Aware.其实 Spring Aware 本来就是 Spring 设计用来框架内部使用的,若使用了 Spring Aware, 你的 bean 将会 和 Spring 框架耦合.
Spring Aware 的目的是为了让 Bean 获得 Spring 容器的服务.因为 ApplicationContext 接口集成了 MessageSource 接口、ApplicationEventPublisher 接口和 ResourceLoader 接口,所以 bean 继承 ApplicationContextAware 可以获得 spring 容器的所有服务,但原则上我们还是用到什么接口就实现什么接口.
示例:
package com.pangu.aware;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {
private String beanName;
private ResourceLoader loader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.loader = resourceLoader;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
public void outputResult(){
System.out.println("Bean 的名称为:"+ beanName);
Resource resource = loader.getResource("classpath:com/pangu/el/test.txt");
try {
System.out.println("ResourceLoader 加载的文件内容为:"+
IOUtils.toString(resource.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.pangu.aware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.pangu.aware")
public class AwareConfig {
}
package com.pangu.aware;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestMain {
@Test
public void run(){
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AwareConfig.class);
AwareService awareService = context.getBean(AwareService.class);
awareService.outputResult();
context.close();
}
}
运行结果:
八月 23, 2018 9:23:43 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@762efe5d: startup date [Thu Aug 23 09:23:43 CST 2018]; root of context hierarchy
Bean 的名称为:awareService
ResourceLoader 加载的文件内容为:盘古开天地...
八月 23, 2018 9:23:43 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@762efe5d: startup date [Thu Aug 23 09:23:43 CST 2018]; root of context hierarchy