项目中,当需要用到Spring 容器本身的功能资源时,Bean 就需要知道容器的存在,才能调用 Spring 所提供的资源,而 Spring Aware就是提供这样的功能,原本也是给 Spring 框架内部使用的。
Spring Aware 的目的就是为了让 Bean 获取容器的服务。ApplicationContext
接口集成了MessageSource
接口,ApplicationEventPublisher
接口和ResourceLoader
接口,如果让 Bean 继承 ApplicationContextAware
可以获得 Spring 容器的所有服务,但原则上有用到什么接口,再实现该接口。
示例
一个业务Bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 package com.springaware;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 { private String beanName; private ResourceLoader loader; @Override public void setResourceLoader (ResourceLoader resourceLoader) { this .loader = resourceLoader; } @Override public void setBeanName (String name) { this .beanName = name; } @SuppressWarnings("deprecation") public void outputResult () throws IOException { System.out.println("Bean的名称:" + beanName); Resource resource = loader.getResource("classpath:com/springaware/test.txt" ); System.out.println("Resource加载的文件内容:" + IOUtils.toString(resource.getInputStream())); } }
配置类
1 2 3 4 5 6 7 8 9 10 package com.springaware;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration @ComponentScan("com.springaware") public class AwareConfig {}
外部资源文件:test.txt
调用执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.springaware;import java.io.IOException;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class MainAware { public static void main (String[] args) throws IOException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (AwareConfig.class); AwareService awareService = context.getBean(AwareService.class); awareService.outputResult(); context.close(); } }
结果
1 2 Bean的名称:awareService Resource加载的文件内容:Hello 中国 SpringCloud