Spring Aware

spring依赖注入的最大亮点就是所有的bean感知不到spring容器的存在,但在实际开发中,我们不可避免的要用到spring容器本身的功能资源,这时,我们就必须意识到容器的存在(废话,都要跟容器进行交互了好么),才能调用spring所提供的资源,这就是所谓的Spring Aware。
Spring Aware的目的是为了让bean获得spring容器的服务。因为ApplicationContext接口集成了MessageSource接口、ApplicationEventPublisher接口和ResourceLoader接口,所以bean继承ApplicationContextAware可以获得spring容器的所有服务,但原则上我们还是用到什么接口就实现什么接口。
-----------示例---------------------------------------------------
service类,方法具体的执行类:

@Service
public class AwareService implements BeanNameAware,ResourceLoaderAware {
    private String beanName;
    private ResourceLoader loader;

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.loader = resourceLoader;
    }

    public void outputResult(){
        System.out.println("bean 的名称为:" + beanName);
        Resource resource = loader.getResource("classpath:com/wzy/bj/aware/test.txt");
        try{
            System.out.println("ResourceLoader加载的文件内容为:" + IOUtils.toString(resource.getInputStream()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
config类,相当于xml配置文件:
@Configuration
@ComponentScan("com.wzy.bj.aware")
public class AwareConfig {
}
测试类,此处直接main方法运行了:
public class AwareMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
        AwareService service = context.getBean(AwareService.class);
        service.outputResult();
        context.close();
    }
}
结果:

 
 

原文地址:https://www.cnblogs.com/nevermorewang/p/8996591.html