zoukankan      html  css  js  c++  java
  • 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();
        }
    }
    
    结果:

     
     

  • 相关阅读:
    export ,export default 和 import 区别 以及用法
    koa2 安装环境
    Webstorm在MAC下的安装方法
    Mac 下搭建vue开发环境
    Mac系统下安装Vue-cli详细步骤
    npm 安装vue 报错Failed at the chromedriver@2.34.0 install script 'node install.js'
    #001 WebStrom SVN使用技巧
    #006 dependencies和devDependencies的区别
    #001 GIT创建分支
    #003 React 组件 继承 自定义的组件
  • 原文地址:https://www.cnblogs.com/nevermorewang/p/8996591.html
Copyright © 2011-2022 走看看