如何手動擷取Spring容器中的bean(ApplicationContextAware 介面)

來源:互聯網
上載者:User

標籤:lan   exce   rda   定義   對象   getbean   public   print   china   

ApplicationContextAware 介面的作用先來看下Spring API 中對於 ApplicationContextAware 這個介面的描述:
 即是說,當一個類實現了這個介面之後,這個類就可以方便地獲得 ApplicationContext 中的所有bean。換句話說,就是這個類可以直接擷取Spring設定檔中,所有有引用到的bean對象。

如何使用 ApplicationContextAware 介面如何使用該介面?很簡單。
1、定義一個工具類,實現 ApplicationContextAware,實現 setApplicationContext方法
 
  1. public class SpringContextUtils implements ApplicationContextAware {
  2. private static ApplicationContext context;
  3. @Override
  4. public void setApplicationContext(ApplicationContext context)
  5. throws BeansException {
  6. SpringContextUtils.context = context;
  7. }
  8. public static ApplicationContext getContext(){
  9. return context;
  10. }
  11. }
如此一來,我們就可以通過該工具類,來獲得 ApplicationContext,進而使用其getBean方法來擷取我們需要的bean。

2、在Spring設定檔中註冊該工具類之所以我們能如此方便地使用該工具類來擷取,正是因為Spring能夠為我們自動地執行 setApplicationContext 方法,顯然,這也是因為IOC的緣故,所以必然這個工具類也是需要在Spring的設定檔中進行配置的。
 
  1. <!--Spring中bean擷取的工具類-->
  2. <bean id="springContextUtils" class="com.zker.common.util.SpringContextUtils" />

3、編寫方法進行使用一切就緒,我們就可以在需要使用的地方調用該方法來擷取bean了。
 
  1. /**
  2. * 利用Ajax實現註冊的使用者名稱重複性校正
  3. * @return
  4. */
  5. public String ajaxRegister() throws IOException {
  6. UserDao userDao = (UserDao)SpringContextUtils.getContext().getBean("userDao");
  7. if (userDao.findAdminByLoginName(loginName) != null
  8. || userDao.findUserByLoginName(loginName) != null) {
  9. message.setMsg("使用者名稱已存在");
  10. message.setStatus(false);
  11. } else {
  12. message.setMsg("使用者名稱可以註冊");
  13. message.setStatus(true);
  14. }
  15. return "register";
  16. }
源碼參考Github地址 --> github.com/deng-cc/KeepLearning/commits/mastercommit id   --> 50f9bd3163aeb126fca4d2e2cf599c6637796d1a

參考連結
  • Spring ApplicationContextAware擷取上下文
  • spring中ApplicationContextAware介面使用理解
  • 手動擷取通過spring mvc注入的bean
  • Spring - 運行時擷取bean(ApplicationContextAware介面)




null

如何手動擷取Spring容器中的bean(ApplicationContextAware 介面)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.