spring boot获取ApplicationContext一直为Null的解决方案

今天在用springbot整合netty写聊天室的时候,用到了自定义SpringUtils获取Spring容器中的对象,但是一直报ApplicationContext为null,最终找到了解决方案,如下

SpringUtils.java (这个类要和springboot启动类放一起)

@Component
@Lazy(false)
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
有点奇葩,问题就解决了

你可能感兴趣的:(bug记录分享)