1. Spring Aware
Spring的依赖注入的最大亮点就是你所有的Bean对Spring容器的存在是没有意识的。即你可以将你的容器替换成别的容器。
实际项目中,不可避免地会用到Spring容器本身的功能资源,这时的Bean必须意识到Spring容器的存在,才能调用Spring所提供的资源,这就是所谓的Spring Aware。
Spring提供的Aware接口如下:
| BeanNameAware | 获取到容器中Bean的名称 |
| BeanFactoryAware | 获得当前bean factory,这样可以调用容器的服务 |
| ApplicationContextAware | 当前的Applicaion context, 这样可以调用容器的服务 |
| MessageSourceAware | 获得message source,这样可以获得文本信息 |
| ApplicationEventPublisher | 应用事件发布器,可以发布事件 |
| ResourceLoaderAware | 获得资源加载器,可以获得外部资源文件 |
Spring Aware的目的是为了让Bean获得Spring容器的服务。
示例:
1) 创建一个test.txt,内容随意
2) Spring Aware演示Bean
1 package com.ws.study.aware; 2 3 import java.io.IOException; 4 5 import org.apache.commons.io.IOUtils; 6 import org.springframework.beans.factory.BeanNameAware; 7 import org.springframework.context.ResourceLoaderAware; 8 import org.springframework.core.io.Resource; 9 import org.springframework.core.io.ResourceLoader; 10 import org.springframework.stereotype.Service; 11 12 // 实现BeanNameAware、ResourceLoaderAware接口,获得Bean名称和资源加载的服务 13 @Service 14 public class AwareService implements BeanNameAware, ResourceLoaderAware{ 15 16 private String beanName; 17 private ResourceLoader loader; 18 19 // 实现ResourceLoaderAware需要重写setResourceLoader 20 public void setResourceLoader(ResourceLoader resourceLoader) { 21 this.loader = resourceLoader; 22 } 23 24 // 实现BeanNameAware需重写setBeanName方法 25 public void setBeanName(String name) { 26 this.beanName = name; 27 } 28 29 public void outputResult(){ 30 System.out.println("Bean的名称为:"+beanName); 31 Resource resource = loader.getResource("classpath:com/ws/study/aware/test.txt"); 32 try { 33 System.out.println("ResourceLoader加载的文件内容为:" 34 +IOUtils.toString(resource.getInputStream())); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 } 39 }