當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
spring boot: spring Aware的目的是为了让Bean获得Spring容器的服务
生活随笔
收集整理的這篇文章主要介紹了
spring boot: spring Aware的目的是为了让Bean获得Spring容器的服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Spring?Aware的目的是為了讓Bean獲得Spring容器的服務
?
//獲取容器中的bean名稱
import org.springframework.beans.factory.BeanNameAware;
//獲得資源加載器,可以獲得額外的資源
import org.springframework.context.ResourceLoaderAware;
?
package ch2.aware; import java.io.IOException;import org.apache.commons.io.IOUtils; //獲取容器中的bean名稱 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;//AwareService是spring的一個組件 @Service //實現BeanNameAware,ResourceLoaderAware資源的接口,獲得名稱和資源加載的服務 public class AwareService implements BeanNameAware,ResourceLoaderAware {private String beanName;private ResourceLoader loader;//實現ResourceLoaderAware需要重寫setResourceLoader@Overridepublic void setResourceLoader(ResourceLoader resourceLoader) {// TODO Auto-generated method stubthis.loader = resourceLoader;}//實現BeanNameAware需要重寫setBeanName@Overridepublic void setBeanName(String name) {// TODO Auto-generated method stubthis.beanName = name; }public void outputResult(){System.out.println("bean的名字為:"+ beanName);Resource resource = loader.getResource("classpath:ch2/aware/test.txt");try {System.out.println("ResourceLoader加載的內容為:" + IOUtils.toString(resource.getInputStream()));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}配置:
package ch2.aware; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;//聲明本類是一個配置類 @Configuration //自動加載ch2.aware包下面的內容 @ComponentScan("ch2.aware") public class AwareConfig {}運行:
package ch2.aware; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args){AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(AwareConfig.class);AwareService awareService = context.getBean(AwareService.class);awareService.outputResult();context.close();}}
?
總結
以上是生活随笔為你收集整理的spring boot: spring Aware的目的是为了让Bean获得Spring容器的服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 孕妇梦到打架见血什么意思
- 下一篇: 做梦梦到金针菇什么意思