提供靜態方法獲取spring bean實例


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

/**
 * 提供靜態方法獲取spring bean實例
 * 
 * @author
 *
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

    //將相關服務注入Spring框架
    @Autowired
    private ImportValidateService _importValidateService;
        
    @Autowired
    private CallBackService _callBackService;
    
    private static ApplicationContext _applicationContext = null;

    private static SpringContextUtils _self;

    public static <T> T getBean(Class<T> requiredType) {
        if (_applicationContext != null) {
            return _applicationContext.getBean(requiredType);
        } else {
            throw new org.springframework.context.ApplicationContextException("ApplicationContext has not been set.");
        }
    }

    public synchronized static ImportValidateService getValidateService() {
        return self()._importValidateService;
    }

    
    public synchronized static CallBackService getCallBackService() {
        return self()._callBackService;
    }

    private static SpringContextUtils self() {
        if (_self == null) {
            if (_applicationContext != null) {
                _self = _applicationContext.getBean(SpringContextUtils.class);
            } else {
                throw new org.springframework.context.ApplicationContextException(
                        "ApplicationContext has not been set.");
            }
        }
        return _self;
    }

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

}

 


免責聲明!

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



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