3.1.1点睛
Spring的依赖注入的最大亮点就是你所有的Bean对Spring容器的存在是没有意识的。即你可以将容器替换成别的容器,如Google Guice,这时Bean之间的耦合度很低。
但是在实际项目中,你不可避免的要用到Spring容器本身的功能资源,这时你的Bean必须要意识到Spring容器的存在,才能调用Spring所提供的资源,这就是所谓的Spring Aware,你的Bean将会和Spring框架耦合。
Spring提供的Aware接口如下。
BeanNameAware:获得到容器中Bean的名称
BeanFactoryAware:获得当前bean factory,这样可以调用容器的服务
ApplicationContextAware:当前的application context,这样可以调用容器的服务
MessageSourceAware:获得message source,这样可以获得广西信息
ApplicationEventPublisherAware:应用事件发布器,可以发布事件,2.5节的DemoPubliser也可实现这个接口来发布事件
ResourceLoaderAware:获得资源加载器可以获得外部资源文件
Spring Aware的目的是为了让Bean获得Spring容器的服务因为ApplicationContext接口集成了MessageSource接口、ApplicationEventPublisher接口和ResourceLoader接口,所以Bean继承ApplicationContextAware可以获得Spring容器的所有服务,但原则上我们还是用到什么接口,就实现什么接口。
3.1.2示例
(1)准备。在com.wisely.highlight_spring4.ch3.aware包下新建一个test.txt,内容随意,给下面的外部资源加载使用。
(2)Spring Aware演示Bean。
package com.wisely.highlight_spring4.ch3.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 { //实现BeanNameAware,ResourceLoaderAware接口,获得Bean名称和资源加载的服务
private String beanName;
private ResourceLoader loader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {//实现ResourceLoaderAware需要重写setResourceLoader。
this.loader=resourceLoader;
}
@Override
public void setBeanName(String name) { //实现BeanNameAware需重写serBeanName方法。
this.beanName=name;
}
public void outputResult(){
System.out.println("Bean的名称为: "+beanName);
Resource resource =
loader.getResource("classpath:com/wisely/highlight_spring4/ch3/aware/test.txt");
try{
System.out.println("ResourceLoader加载的文件内容为:"+IOUtils.toString(resource.getInputStream()));
}catch (IOException e) {
e.printStackTrace();
}
}
}
(3)配置类。
package com.wisely.highlight_spring4.ch3.aware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.aware")
public class AwareConfig {
}
(4)运行。
package com.wisely.highlight_spring4.ch3.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();
}
}
运行结果