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();
        }
    }
    
    结果:

     
     

  • 相关阅读:
    C++/CLI中的资源清理(Destructor,Finalizer
    c++/cli 之数据库操作
    利用139,189,yahoo等邮箱短信提示来免费发短信提示
    小例子复习下委托的应用
    c++/cli 之日志记录
    c++/cli 之异步Socket完成端口实例
    C++/CLI, Finalize and Dispose
    C/C++的位运算符操作
    实现自定义控件与背景图完全重叠
    RichTextBox与NotifyIcon简单模仿QQ效果
  • 原文地址:https://www.cnblogs.com/nevermorewang/p/8996591.html
Copyright © 2011-2022 走看看