最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot獲取ApplicationContext的3種方式

 更新時(shí)間:2019年09月24日 10:43:57   作者:A 是小阿怪啊  
這篇文章主要為大家詳細(xì)介紹了SpringBoot獲取ApplicationContext的3種方式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

ApplicationContext是什么?

簡(jiǎn)單來(lái)說(shuō)就是Spring中的容器,可以用來(lái)獲取容器中的各種bean組件,注冊(cè)監(jiān)聽(tīng)事件,加載資源文件等功能。

Application Context獲取的幾種方式

1 直接使用Autowired注入

@Component
public class Book1 {

 @Autowired
 private ApplicationContext applicationContext;

 public void show (){
  System.out.println(applicationContext.getClass());
 }
}

2 利用 spring4.3 的新特性

使用spring4.3新特性但是存在一定的局限性,必須滿(mǎn)足以下兩點(diǎn):

1) 構(gòu)造函數(shù)只能有一個(gè),如果有多個(gè),就必須有一個(gè)無(wú)參數(shù)的構(gòu)造函數(shù),此時(shí),spring會(huì)調(diào)用無(wú)參的構(gòu)造函數(shù)

2) 構(gòu)造函數(shù)的參數(shù),必須在spring容器中存在

@Component
public class Book2 {

 private ApplicationContext applicationContext;

 public Book2(ApplicationContext applicationContext){
  System.out.println(applicationContext.getClass());
  this.applicationContext=applicationContext;
 }

 public void show (){
  System.out.println(applicationContext.getClass());
 }

}

3 實(shí)現(xiàn)spring提供的接口 ApplicationContextAware

spring 在bean 初始化后會(huì)判斷是不是ApplicationContextAware的子類(lèi),調(diào)用setApplicationContext()方法, 會(huì)將容器中ApplicationContext傳入進(jìn)去

@Component
public class Book3 implements ApplicationContextAware {

 private ApplicationContext applicationContext;

 public void show (){
  System.out.println(applicationContext.getClass());
 }

 @Override
 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  this.applicationContext = applicationContext;
 }
}

結(jié)果獲取三次:

class org.springframework.context.annotation.AnnotationConfigApplicationContext
class org.springframework.context.annotation.AnnotationConfigApplicationContext
class org.springframework.context.annotation.AnnotationConfigApplicationContext

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

舞阳县| 洛阳市| 滨州市| 山东| 深水埗区| 文成县| 玉树县| 长治县| 柏乡县| 江永县| 巨鹿县| 沙湾县| 乌拉特中旗| 台南县| 东宁县| 池州市| 广德县| 清新县| 弥渡县| 丹寨县| 海盐县| 宝清县| 苍山县| 桂平市| 信丰县| 宁德市| 陇西县| 承德市| 东方市| 宝应县| 塔城市| 镇远县| 泰州市| 和静县| 安福县| 出国| 平谷区| 英超| 新晃| 宿迁市| 南郑县|