哈哈,终于把分布式的课程演讲给混过去了,下面开始随便自己学点东西。
正题:SpringAware--------在实际项目中,用到spring容器的本省功能资源,这是Bean必须意识到Spring容器的存在,才能调用Spring容器所提供的资源,这就是所谓的Spring Aware.
分两部分,一部分演示书上的列子,一部分用SpringBoot改进,注此列是参照SpringBoot的一本书学习而来,具体不记得了。
一 BeanNameAware--------------获得容器中Bean的名字
BeanFactoryAware------------获得当前容器的BeanFactory,这样可以调用容器的服务
ApplicationContextAware-----获得当前容器的ApplicationContext,这样可以调用容器的服务
ApplicationEventPublisherAware----应用时间发布器,可以发布事件
ResourceLoaderAware-------获得资源加载器,可以获得外部文件
1 继承两个接口并分别重写,BeanNameAware,ResourceLoaderAware这样就分别从容器总拿到了Bean和资源加载器。
package org.sselab.service; 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; /** * Created by pinker on 2016/11/8. */@Servicepublic class AwareService implements BeanNameAware, ResourceLoaderAware { private String name; private ResourceLoader loader; @Override public void setBeanName(String s) { this.name = s; } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.loader = resourceLoader; } public void outputResult() { System.out.println("Bean的名称是:" + name); Resource resource = loader.getResource("classpath:test.txt"); try { System.out.println(IOUtils.toString(resource.getInputStream())); } catch (IOException e) { e.printStackTrace(); } }}2 配置类
package org.sselab.conf; import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration; /** * Created by pinker on 2016/11/8. */@Configuration@ComponentScan("org.sselab")public class AwareConfig { }3 运行主类
package org.sselab; import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.sselab.conf.AwareConfig;import org.sselab.service.AwareService; /** * Created by pinker on 2016/11/8. */public class Application { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class); AwareService service = context.getBean(AwareService.class); service.outputResult(); context.close(); }} 分析一下,2是个配置类,肯定可以用SpringBootApplication来代替,这里我们伪造一个访问资源,看看能不能输出。
public String getContext(){ Resource resource =loader.getResource("classpath:test.txt"); String result= null; try { result = IOUtils.toString(resource.getInputStream()); } catch (IOException e) { e.printStackTrace(); } return result;}然后构造访问的controller和主启动类OK了,完成了!实验结果如果所想,其实就是因为少了配置和采用了自动注入,所以没有本质的区别。
时间: 2024-07-28 23:55:52