监听器中@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);

 

posted @ 2022-06-16 16:50  企业级理解  阅读(533)  评论(0编辑  收藏  举报