一. 点睛
Spring
的依赖注入的最大亮点就是你所有的Bean
对Spring
容器的存在是没有意识的。即你可以将你的容器替换成别的容器,例如Goggle Guice
,这时Bean
之间的耦合度很低。
但是在实际的项目中,我们不可避免的要用到Spring
容器本身的功能资源,这时候Bean
必须要意识到Spring
容器的存在,才能调用Spring
所提供的资源,这就是所谓的Spring
Aware
。其实Spring
Aware
本来就是Spring
设计用来框架内部使用的,若使用了Spring
Aware
,你的Bean
将会和Spring
框架耦合。
Spring
提供的Aware
接口如下表所示:
Spring提供的Aware接口
BeanNameAware | 获得到容器中Bean的名称 |
---|---|
BeanFactoryAware | 获得当前bean factory,这样可以调用容器的服务 |
ApplicationContextAware* | 获得当前application context,这样可以调用容器的服务 |
MessageSourceAware | 获得message source这样可以获得文本信息 |
ApplicationEventPublisherAware | 应用事件发布器,可以发布事件 |
ResourceLoaderAware | 获得资源加载器,可以获得外部资源文件 |
Spring
Aware
的目的是为了让Bean
获得Spring
容器的服务。因为ApplicationContext
接口集成了MessageSource
接口,ApplicationEventPublisherAware
接口和ResourceLoaderAware
接口,所以Bean
继承ApplicationContextAware
可以获得Spring
容器的所有服务,但原则上我们还是用到什么接口就实现什么接口。
二. 示例
1. 准备。
在org.light4j.sping4.senior.aware
包下新建一个test.txt
,内容随意,给下面的外部资源加载使用。
2. Spring Aware演示Bean
package org.light4j.sping4.senior.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:org/light4j/sping4/senior/aware/test.txt");
try{
System.out.println("ResourceLoader加载的文件内容为: " + IOUtils.toString(resource.getInputStream()));
}catch(IOException e){
e.printStackTrace();
}
}
}
代码解释:
① 实现
BeanNameAware
,ResourceLoaderAware
接口,获得Bean
名称和资源加载的服务。
② 实现ResourceLoaderAware
需要重写setResourceLoader
方法。
③ 实现BeanNameAware
需要重写setBeanName
方法。
3. 配置类
package org.light4j.sping4.senior.aware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.light4j.sping4.senior.aware")
public class AwareConfig {
}
4. 运行
package org.light4j.sping4.senior.aware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
AwareService awareService = context.getBean(AwareService.class);
awareService.outputResult();
context.close();
}
}
运行结果如下图所示:
5. 源代码示例:
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » Spring4.x高级话题(一):Spring Aware