通過實現ApplicationContextAware介面動態擷取bean

來源:互聯網
上載者:User

標籤:

轉載自:http://penghuaiyi.iteye.com/blog/2042296

情境:

在代碼中需要動態擷取spring管理的bean

代碼:

SpringContextUtils.java

package com.winner.utils;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;/** * Spring的工具類,用來獲得設定檔中的bean */@Componentpublic class SpringContextUtils implements ApplicationContextAware {    private static ApplicationContext applicationContext;    /**     *  當繼承了ApplicationContextAware類之後,那麼程式在調用 getBean(String)的時候會自動調用該方法,     * 不用自己操作     */    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        SpringContextUtils.applicationContext = applicationContext;    }    /***     * 根據一個bean的id擷取設定檔中相應的bean     */    public static Object getBean(String beanId) throws BeansException {        if (applicationContext.containsBean(beanId)) {            applicationContext.getBean(beanId);        }        return null;    }    /***     * 根據一個bean的類型擷取設定檔中相應的bean     */    public static <T> T getBeanByClass(Class<T> requiredType) throws BeansException {        return applicationContext.getBean(requiredType);    }    /**     * 如果BeanFactory包含一個與所給名稱匹配的bean定義,則返回true     */    public static boolean containsBean(String name) {        return applicationContext.containsBean(name);    }    public static ApplicationContext getApplicationContext() {        return SpringContextUtils.applicationContext;    }}

這幾個註解所在的包是

<dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-context</artifactId>    <version>4.2.5.RELEASE</version></dependency>

SpringContextUtils必須放在Spring容器中

要麼在xml設定檔中聲明,要麼加上註解

 

 

通過實現ApplicationContextAware介面動態擷取bean

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.