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("根据名字获取时这里要和你在别地方注入过的对象名一致");

猜你喜欢

转载自blog.csdn.net/qq_32475739/article/details/79107936