项目中,当需要用到Spring容器本身的功能资源时,Bean就需要知道容器的存在,才能调用 Spring 所提供的资源,而 Spring Aware就是提供这样的功能,原本也是给 Spring 框架内部使用的。
Spring Aware 的目的就是为了让 Bean 获取容器的服务。ApplicationContext
接口集成了MessageSource
接口,ApplicationEventPublisher
接口和ResourceLoader
接口,如果让 Bean 继承 ApplicationContextAware
可以获得 Spring 容器的所有服务,但原则上有用到什么接口,再实现该接口。
示例
一个业务Bean
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; /** * Spring Aware提供容器服务 * @author Rocky * */ @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())); } }
配置类
package com.springaware; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.springaware") public class AwareConfig { }
外部资源文件:test.txt
Hello 中国 SpringCloud
调用执行
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(); } }
结果
Bean的名称:awareService Resource加载的文件内容:Hello 中国 SpringCloud
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载