spring boot 获取ApplicationContext

使用springboot开发时,有一个需求是在过滤器filter中判断用户登录的信息,于是我写了一个UserService,并且在过滤器中实现自动装配(@Autowired)。使用springboot自带的服务器启动时没有问题,但是使用外部的Tomcat启动时就不能实现自动装配了,报NullPointerException错误。搞了半天不知道什么原因,我就想到用ApplicationContext的方式来获取UserService,具体如下:

  1. 新建SpringContext类(这个类要和springboot启动类放一起):
@Component
@Lazy(false)
public class SpringContext 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);
    }
}
  1. 使用:
//通过class获得bean
UserService userService= SpringContext.getBean(UserService.class);
//通过name获得bean
UserService userService= SpringContext.getBean("userService");
//通过name,以及Clazz返回指定的Bean
UserService userService= SpringContext.getBean("userService",UserService.class);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容