• 外置 tomcat启动Spring Boot程序模式下解决过滤器注入bean的空指针问题


      在上一篇博文中,一般是可以解决过滤器注入bean的空指针问题的,但我们跑在服务器上的Spring Boot程序一般是使用外置tomcat来启动的,

    1      public static void main(String[] args) throws InterruptedException {
    2          ApplicationContext context = SpringApplication.run(Application.class, args);
    3          SpringContextUtil.setApplicationContext(context);
    4      }

    这与我们在ide上直接run Application.java是不一样的,也会发生空指针异常,因为直接启动tomcat的方式上面的第三行没有执行,context注入失败。因此我们需要换一种Spring context的注入方式

     1 @Component
     2 public class SpringContextUtil implements ApplicationContextAware {
     3     private static ApplicationContext applicationContext;
     4     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
     5         SpringContextUtil.applicationContext = applicationContext;
     6     }
     7     public static ApplicationContext getApplicationContext() {
     8         return applicationContext;
     9     }
    10     
    11     //通过名字获取上下文中的bean
    12     public static Object getBean(String name){
    13         return applicationContext.getBean(name);
    14     }
    15     
    16     //通过类型获取上下文中的bean
    17     public static Object getBean(Class<?> requiredType){
    18         return applicationContext.getBean(requiredType);
    19     }
    20 }

    就可以正常使用Bean组件了,经验证 问题得以解决

  • 相关阅读:
    常见排序算法总结(一)
    27.移除元素
    556. 下一个更大元素 III
    503. 下一个更大元素 II
    496.下一个更大元素Ⅰ
    汇编基础
    SQL回顾
    Pandas整理
    爬取中公网新闻时政
    Python合并Excel表格
  • 原文地址:https://www.cnblogs.com/tjqBlog/p/9403656.html
Copyright © 2020-2023  润新知