Spring Aware的目的是为了让Bean获得Spring容器的服务
//获取容器中的bean名称
import org.springframework.beans.factory.BeanNameAware;//获得资源加载器,可以获得额外的资源import org.springframework.context.ResourceLoaderAware;
package ch2.aware;import java.io.IOException;import org.apache.commons.io.IOUtils;//获取容器中的bean名称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;//AwareService是spring的一个组件@Service//实现BeanNameAware,ResourceLoaderAware资源的接口,获得名称和资源加载的服务public class AwareService implements BeanNameAware,ResourceLoaderAware { private String beanName; private ResourceLoader loader; //实现ResourceLoaderAware需要重写setResourceLoader @Override public void setResourceLoader(ResourceLoader resourceLoader) { // TODO Auto-generated method stub this.loader = resourceLoader; } //实现BeanNameAware需要重写setBeanName @Override public void setBeanName(String name) { // TODO Auto-generated method stub this.beanName = name; } public void outputResult() { System.out.println("bean的名字为:"+ beanName); Resource resource = loader.getResource("classpath:ch2/aware/test.txt"); try { System.out.println("ResourceLoader加载的内容为:" + IOUtils.toString(resource.getInputStream())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
配置:
package ch2.aware;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;//声明本类是一个配置类@Configuration//自动加载ch2.aware包下面的内容@ComponentScan("ch2.aware")public class AwareConfig {}
运行:
package ch2.aware;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(AwareConfig.class); AwareService awareService = context.getBean(AwareService.class); awareService.outputResult(); context.close(); } }