本文主要写了几个关于Spring Aware,多线程,计划任务(定时任务),条件注解,组合注解,元注解,Spring测试的小例子以及关于@Enable*注解的工作原理的理解。


 

Spring Aware

  简介:

    Spring的依赖注入的最大亮点就是你所有的Bean对Spring容器的存在是没有意识的。即你可以将你的容器替换成别的容器,如Google Guice,这是Bean之间的耦合度很低。

    但是在实际项目中,有时会不可避免的要用到Spring容器本身的功能资源,这是你的Bean必须要意识到Spring容器的存在,才能调用Spring所提供的资源,这就是Spring Aware。

    其实Spring Aware本来就是Spring设计用来框架内部使用的,若使用了Spring Aware,你的Bean将会和Spring框架耦合。

  例子:

 1 package com.wisely.highlight_spring4.ch3.aware;
 2 
 3 import org.apache.commons.io.IOUtils;
 4 import org.springframework.beans.factory.BeanNameAware;
 5 import org.springframework.context.ResourceLoaderAware;
 6 import org.springframework.core.io.Resource;
 7 import org.springframework.core.io.ResourceLoader;
 8 import org.springframework.stereotype.Service;
 9 
10 import java.io.IOException;
11 
12 /**
13  * Spring Aware演示Bean
14  * 实现BeanNameAware、ResourceLoaderAware接口,获得Bean名称和资源加载的服务。
15  */
16 @Service
17 public class AwareService implements BeanNameAware, ResourceLoaderAware {//1
18 
19     private String beanName;
20     private ResourceLoader loader;
21     //实现ResourceLoaderAware需重写setResourceLoader方法
22     @Override
23     public void setResourceLoader(ResourceLoader resourceLoader) {//2
24         this.loader = resourceLoader;
25     }
26     //实现BeanNameAware需重写setBeanName方法
27     @Override
28     public void setBeanName(String name) {//3
29         this.beanName = name;
30     }
31 
32     public void outputResult() {
33         System.out.println("Bean的名称为:" + beanName);
34         Resource resource = loader.getResource("classpath:com/wisely/highlight_spring4/ch3/aware/test.txt");
35         try {
36             System.out.println("ResourceLoader加载的文件内容为: " + IOUtils.toString(resource.getInputStream()));
37         } catch (IOException e) {
38             e.printStackTrace();
39         }
40     }
41 }
Spring Aware演示Bean

相关文章:

  • 2021-05-30
  • 2021-08-17
  • 2021-12-19
  • 2021-05-25
  • 2021-06-27
  • 2021-11-06
  • 2021-07-02
  • 2022-01-29
猜你喜欢
  • 2022-12-23
  • 2021-04-19
  • 2022-12-23
  • 2022-12-23
  • 2022-01-15
  • 2021-09-06
  • 2021-11-19
相关资源
相似解决方案