第八章 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
- 第八章 Spring Aware扩展
- Spring-Aware
- # Spring Aware
- Spring Aware
- Spring Aware
- Spring Aware (Spring 感知)
- Spring:Aware和事件
- spring-aware接口
- Spring中的Aware
- spring-Aware接口
- Spring Bean--Aware接口
- Spring -- 3.Aware
- spring之aware接口
- spring的Aware
- Spring Aware理解
- Spring中的Aware接口
- Spring4.x:Spring Aware
- Spring的Aware
- python中除号/和//的区别
- js正则表达式验证密码格式的几种情况总结
- Mac OS X启动项详解
- linux电脑插入U盘自动挂载而不自动打开
- struts开发流程及详细
- 第八章 Spring Aware扩展
- windows搭建gcc开发环境(msys2)
- 计算Label高度swift
- _snprintf_s, _snprintf_s_l, _snwprintf_s, _snwprintf_s_l
- VS2015 快捷键
- mxnet im2re.py
- mybatis xml中的小于的写法,like模糊查询的写法
- 小白日记——下载进度的顶部通知
- 第九章 Spring多线程处理