【BUG解决】Spring boot 中Handler,Filter注入 Service、Repositoy为null

 新建 springBeanUtil.java




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

/**
 * @author: 马宾
 * @DATA: 2020/11/22  16:27
 * @description: SpringContextUtils todo
 * @Belong: JuLink-Iot
 **/


@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

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

    public static Object getBeanByName(String beanName) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> type) {
        return applicationContext.getBean(type);
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

 然后在需要注入的地方,这样用:

 private AlarmService alarmService;
   this.alarmService = SpringBeanUtil.getBean(AlarmService.class);

或:

 private static NettyMessageHandleService nettyMessageHandleService;

    static {
        nettyMessageHandleService = SpringBeanUtil.getBean(NettyMessageHandleService.class);
    }

主要思路就是从springboot容器里去取。

上一篇:移动端测试


下一篇:Spring中BeanFactory与ApplicationContext关系