1. 程式人生 > >實現ApplicationContextAware介面,java(new或者java反射獲取的物件)中獲取spring容器的bean

實現ApplicationContextAware介面,java(new或者java反射獲取的物件)中獲取spring容器的bean

本文參考了https://blog.csdn.net/bailinbbc/article/details/76446594,其實是拷貝了很多內容:

在Web應用中,Spring容器通常採用宣告式方式配置產生:開發者只要在web.xml中配置一個Listener,該Listener將會負責初始化Spring容器,MVC框架可以直接呼叫Spring容器中的Bean,無需訪問Spring容器本身。在這種情況下,容器中的Bean處於容器管理下,無需主動訪問容器,只需接受容器的依賴注入即可。

但在某些特殊的情況下,Bean需要實現某個功能,但該功能必須藉助於Spring容器才能實現,此時就必須讓該Bean先獲取Spring容器,然後藉助於Spring容器實現該功能。為了讓Bean獲取它所在的Spring容器,可以讓該Bean實現ApplicationContextAware介面。

下面示例為實現ApplicationContextAware的工具類,可以通過其它類引用它以操作spring容器及其中的Bean例項。
 

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

/**
 * @program: 
 * @description: 獲取spring容器中bean
 * @author: 
 * @create: 2018-12-05 10:47
 **/
@Component
public class BeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

    /**
     * 從靜態變數applicationContext中得到Bean, 自動轉型為所賦值物件的型別.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 從靜態變數applicationContext中得到Bean, 自動轉型為所賦值物件的型別.
     */
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }
}

其中@Component註解必須有。

@Override
    public String getData(String[] values, Object type) {
        if(values == null || values.length == 0){
            LOG.error("字典對照引數異常values:{}",values);
            return "";
        }
        if(type != null) {
            try {
                DictRlatService dictRlatService = BeanUtils.getBean(DictRlatService.class);
                String value = dictRlatService.selectDictCode(values[0], type.toString());
                return value;
            } catch (Exception e) {
                LOG.error("字典對照異常,values[0]:{},type:{}",values[0],type.toString(),e);
            }
        }else{
            LOG.error("字典對照引數異常type:{}",type);
        }
        return "";
    }

本人對spring理解不深入,僅供參考。