從spring容器中取出注入的bean


從spring容器中取出注入的bean 工具類,代碼如下:

package com.hyzn.fw.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/** 
 * @ClassName: SpringBeanUtil
 * @Description: TODO  Spring獲取bean的工具類,可用於在線程里面獲取bean 
 *                  需要在 類上 標注 @Component ,否則沒有將此工具類 注入到spring容器中
 * @author xbq
 * @version 1.0
 * @date 2017-2-21 下午2:30:38
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware{
    
    private static ApplicationContext applicationContext = null;  
      
    // 獲取ApplicationContext對象
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
        SpringBeanUtil.applicationContext = applicationContext;  
    }  
  
    /**
     * @Title: getBeanByName
     * @Description: TODO  通過bean的名字來獲取Spring容器中的bean
     * @param beanName
     * @return
     * @return: Object
     */
    public static Object getBeanByName(String beanName) {  
        if (applicationContext == null){  
            return null;  
        }  
        return applicationContext.getBean(beanName);  
    }  
  
    public static <T> T getBean(Class<T> type) {  
        return applicationContext.getBean(type);  
    }  
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM