监听器中@autowired@Resource无法注入bean
背景:今天需要在项目中写一个定时任务来扫描用户会员到期信息,写了一个监听器,发现@autowired@Resource不管怎么注入都是null
原因:listener、fitter都不是Spring容器管理的,无法在这些类中直接使用Spring注解的方式来注入我们需要的对象
办法:写一个bean工厂,从spring的上下文WebApplicationContext 中获取
package com.suntek.app.common.context; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * Spring上下文 * */ @Component public class SpringContext implements ApplicationContextAware { // Spring应用上下文环境 private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContext.applicationContext = applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 获取bean * * @param name * @param clazz * @return */ public static <T> T getBean(String name, Class<T> clazz) { return applicationContext.getBean(name, clazz); } }
然后就可以通过下边的方法来获取
SpringContext.getBean("userServiceConsumer", UserServiceConsumer.class);
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步