Quartz任務執行無法注入Bean問題解決

1.說明

1.多線程Bean無法注入,例如在任務執行中具體原因不太瞭解,有待深入學習

2.解決

1.編寫一個SpringBean工具類,通過這個工具類獲取Spring上下文,從而獲取到Bean對象


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

public class SpringBeanUtil implements ApplicationContextAware{

    private static ApplicationContext applicationContext = null;

    /**
     * 實現接口方法
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {    
        SpringBeanUtil.applicationContext = applicationContext;
    }

    /**
     * 根據beanName返回相應的對象
     * @param beanName
     * @return
     */
    public static Object getBeanByName(String beanName) {  
        if (applicationContext == null){  
            return null;  
        }  
        return applicationContext.getBean(beanName);  
    }  

    /**
     * 根據bean的類型返回一個對象
     * @param type
     * @return
     */
    public static <T> T getBean(Class<T> type) {  
        return applicationContext.getBean(type);  
    }  
}

2.加載到Spring,在Spring的XML文件中加入這句話

<!--路徑改成你的工具類的路徑-->
<bean id="springBeantUtil" class="com.keisunique.SpringBeanUtil"/>

3.獲取對象

//根據名字獲取
SpringBeanUtil.getBeanByName("根據名字獲取時這裏要和你在別地方注入過的對象名一致");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章