SpringBoot中怎么獲取ApplicationContext,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
ApplicationContext是什么?
簡單來說就是Spring中的容器,可以用來獲取容器中的各種bean組件,注冊監聽事件,加載資源文件等功能。
Application Context獲取的幾種方式
1 直接使用Autowired注入
@Componentpublic class Book1 { @Autowired private ApplicationContext applicationContext; public void show (){ System.out.println(applicationContext.getClass()); }}
2 利用 spring4.3 的新特性
使用spring4.3新特性但是存在一定的局限性,必須滿足以下兩點:
1) 構造函數只能有一個,如果有多個,就必須有一個無參數的構造函數,此時,spring會調用無參的構造函數
2) 構造函數的參數,必須在spring容器中存在
@Componentpublic 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 實現spring提供的接口 ApplicationContextAware
spring 在bean 初始化后會判斷是不是ApplicationContextAware的子類,調用setApplicationContext()方法, 會將容器中ApplicationContext傳入進去
@Componentpublic 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; }}
結果獲取三次:
class org.springframework.context.annotation.AnnotationConfigApplicationContextclass org.springframework.context.annotation.AnnotationConfigApplicationContextclass org.springframework.context.annotation.AnnotationConfigApplicationContext
看完上述內容,你們掌握SpringBoot中怎么獲取ApplicationContext的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。