Spring 高级话题-Spring Aware
【博文目录>>>】
【项目源码>>>】
【Spring Aware】
Spring的依赖注入的最大亮点就是所有的Bean 对Spring 容器的存在是没有意识的。你可以将容器替换成别的容器,如Google Guice ,这时Bean 之间的耦合度很低。
但是在实际项目中,你不可避免的要用到Spring 容器本身的功能资源,这时你的Bean 必须要意识到Spring 容器的存在,才能调用Spring 所提供的资源,这就是所谓的Spring Aware。
其实Spring Aware 本来就是Spring设计用来框架内部使用的,若使用了Spring Aware ,你的Bean 将会和Spring 框架糯合。
Spring 提供的Aware 接口:
类名 | 作用 |
---|---|
BeanNameAware | 获得到容器中Bean 的名称 |
BeanFactoryAware | 获得当前bean factory ,即创建Bean的工厂 |
ApplicationContextAware* | 当前的application context ,获取当前应用上下文 |
MessageSourceAware | 获得message source ,这样可以获得文本信息 |
ApplicationEventPublisherAware | 应用事件发布器,可以发布事件 |
ResourceLoaderAware | 获得资源加载器,可以获得外部资源、文件 |
Spring Aware 的目的是为了让Bean 获得Spring 容器的服务。因为ApplicationContext 接口集成了MessageSource 接口、ApplicationEventPublisher 接口和ResourceLoader 接口,所以Bean 继承ApplicationContextAware 可以获得Spring 容器的所有服务,原则上用到什么接口,就实现什么接口。
【代码实现】
package com.example.spring.framework.aware;
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;
import java.io.IOException;
/**
* ①实现BeanNameAware、ResourceLoaderAware接口,获得Bean 名称和资源、加载的服务。
* ②实现ResourceLoaderAware 需章写setResourceLoadero
* ③实现BeanNameAware需重写setBeanName 方法。
*
* Author: 王俊超
* Date: 2017-07-11 07:47
* All Rights Reserved !!!
*/
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {
private String beanName;
private ResourceLoader loader;
@Override
public void setBeanName(String name) {
this.beanName = name;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.loader = resourceLoader;
}
public void outputResult() {
System.out.println("Bean的名称为:" + beanName);
Resource resource = loader.getResource(
"classpath:com/example/spring/framework/aware/test.txt");
try {
System.out.println("ResourceLoader加载的文件内容为: " +
IOUtils.toString(resource.getInputStream(), "utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.example.spring.framework.aware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Author: 王俊超
* Date: 2017-07-11 07:50
* All Rights Reserved !!!
*/
@Configuration
@ComponentScan("com.example.spring.framework.aware")
public class AwareConfig {
}
package com.example.spring.framework.aware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Author: 王俊超
* Date: 2017-07-11 07:50
* All Rights Reserved !!!
*/
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();
}
}