zoukankan      html  css  js  c++  java
  • springboot自定义filter获取spring容器bean对象

      今天在自己定义的filter中,想要直接注入spring容器的其它bean进行操作,发现不能正常的注入:

    原因:web容器加载顺序导致, 加载顺序是listener——filter——servlet,当项目启动时,filter先于servlet初始化, 而Spring中默认bean的初始化是在Servlet后进行的,所以会注入失败

    解决办法:接下来编写一个SpringUtils进行手动注入bean

     1 @Component
     2 public class SpringUtils implements ApplicationContextAware{
     3     private static ApplicationContext applicationContext;
     4  
     5     @Override
     6     public void setApplicationContext(ApplicationContext applicationContext)
     7             throws BeansException {
     8         if (SpringUtils.applicationContext == null) {
     9             SpringUtils.applicationContext = applicationContext;
    10         }
    11  
    12     }
    13  
    14     public static ApplicationContext getApplicationContext() {
    15         return applicationContext;
    16     }
    17  
    18     //根据name
    19     public static Object getBean(String name) {
    20         return getApplicationContext().getBean(name);
    21     }
    22  
    23     //根据类型
    24     public static <T> T getBean(Class<T> clazz) {
    25         return getApplicationContext().getBean(clazz);
    26     }
    27  
    28     public static <T> T getBean(String name, Class<T> clazz) {
    29         return getApplicationContext().getBean(name, clazz);
    30     }
    31  }

    在需要使用的filter中,直接使用工具类拿到相应的对象

  • 相关阅读:
    hadoop之 解析HDFS的写文件流程
    Linux之 手动释放内存
    Heka 的编译
    go get 下载需要的相关工具
    峰值计算的方法
    thrift简介
    Bazaar 版本控制工具
    Homebrew
    虚拟机下centos时间不正确的方便解决方法
    golang 应用的部署相关技术
  • 原文地址:https://www.cnblogs.com/yinfengjiujian/p/11749647.html
Copyright © 2011-2022 走看看