第八章 Spring Aware扩展

来源:互联网 发布:unity3d开始界面添加 编辑:程序博客网 时间:2024/06/17 12:27

Spring提供的Aware接口

BeanNameAware:获得容器中Bean的名称
BeanFactoryAware:获得当前Bean Factory,这样可以调用容器的服务
ApplicationContextAware:获得当前Application Context,这样可以调用容器的服务
MessageSourceAware:获得Message Source,这样可以获得文本信息
ApplicationEventPublisherAware:应用事件发布器,可以发布事件
ResourceLoaderAware:获得资源加载器,可以获得外部资源文件>

因为ApplicationContext接口集成了MessageSource接口、ApplicationEventPublisher接口、ResourceLoader接口,所以Bean继承ApplicationContextAware可以获得Spring容器的所有服务。

上代码

package demo2.service;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;@Servicepublic class AwareService implements BeanNameAware, ResourceLoaderAware {    private String beanName;    private ResourceLoader rl;    @Override    public void setResourceLoader(ResourceLoader resourceLoader) {        this.rl = resourceLoader;    }    @Override    public void setBeanName(String name) {        this.beanName = name;    }    public void outputResult() {        System.out.println("Bean的名称为:" + beanName);        Resource resource = rl.getResource("classpath:demo2/service/test.txt");        System.out.println("加载test.txt文件的内容为");        try {            System.out.println(IOUtils.toString(resource.getInputStream()));        } catch (IOException e) {            e.printStackTrace();        }    }}

运行

package demo2;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import demo2.config.DIConfig;import demo2.service.AwareService;public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext();        cxt.getEnvironment().setActiveProfiles("dev");        cxt.register(DIConfig.class);        cxt.refresh();        AwareService ds = cxt.getBean(AwareService.class);        ds.outputResult();        cxt.close();    }}

结果

Bean的名称为:awareService加载test.txt文件的内容为xxxxxxxx
0 0
原创粉丝点击