今天學習到了spring aware ,特地百度了下這方面的知識,現在談下我的理解。
Spring
的依賴注入的最大亮點就是你所有的Bean
對Spring
容器的存在是沒有意識的。即你可以將你的容器替換成別的容器,例如Goggle Guice
,這時Bean
之間的耦合度很低。
但是在實際的項目中,我們不可避免的要用到Spring
容器本身的功能資源,這時候Bean
必須要意識到Spring
容器的存在,才能調用Spring
所提供的資源,這就是所謂的Spring
Aware
。其實Spring
Aware
本來就是Spring
設計用來框架內部使用的,若使用了Spring
Aware
,你的Bean
將會和Spring
框架耦合。
-------------------------------------
ps:這段話很官(抽)方(象),我的理解是,spring aware 的這些接口的存在,讓我們可以獲取、修改beanName(getBeanName)、事件發布(applicationContext.publishEvent)等。具體場景,我暫時不了解,百度也找不到,估計是會在一些架構方面做文章吧。
spring aware 以下是幾個常用的接口:
1、ApplicationContextAware 能獲取Application Context調用容器的服務
2、BeanNameAware 提供對BeanName進行操作
3、ApplicationEventPublisherAware 主要用於事件的發布
4、BeanClassLoadAware 相關的類加載器
5、BeanFactoryAware 聲明BeanFactory的
下面直接上代碼:
定義一個Bean AwareSevice ,繼承BeanNameAware 和ResourceLoaderAware接口
package com.abc.service; import org.springframework.beans.factory.BeanNameAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Service; import java.io.IOException; @Service public class AwareService implements BeanNameAware, ResourceLoaderAware { private String beanName; private ResourceLoader resourceLoader; @Override public void setBeanName(String s) { this.beanName=s+"111"; } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader=resourceLoader; } public void outputResult() { System.err.println("Bean名字是:" + beanName); Resource resource = resourceLoader.getResource("classpath:application.yml"); try { System.err.println("resource加載的文件內容是:" + resource.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } }
可以看到,這里提供了setBeanName()和setResourceLoader(),用於設置BeanName和ResourceLoader。而我們沒有繼承這個的時候,用getBeanName()和getResourceLoader() 來獲取的beanName和resourceLoader。
設置一個config,用來掃描這個包
package com.abc.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.abc.service") public class AwareConfig { }
調動service 的結果如下:
可以看到,這里的AwareService 的BeanName的確被改變了。(ps,就是不知道這樣做實際上有什么意義)