HafuHafu

  • 首页
  • 技术
    • 编程
    • 教程
  • 资源
  • 综合
    • 杂谈
  • ACG
    • Anime & Comic
    • Game
  • 用户中心
    • 登录
  1. 首页
  2. 编程
  3. 正文

SpringBoot关于在Filter中自动注入(@AutoWired)为null的解决方案

2019-04-13 1963点热度 2人点赞 1条评论

前两天在整合Shiro框架,因为要拦截所有请求并自定义验证方式,所以需要自定义Filter来过滤请求。但是我试图在Filter中通过@Value的方式获取自定义配置文件的值时,却发现总是为null,说明Spring并没有为我们注入这个属性。后来又尝试了@AutoWired发现也是为null。

原因应该是因为过滤器的启动顺序在servlet之前,filter初始化时bean还未初始化,所以总是为空。经过一番查找,最终发现了一个个人感觉比较可靠的解决方案。即写一个工具类实现ApplicationContextAware接口,通过该工具类手动获取配置文件对应的类,从而间接获取配置文件的属性。

以下是所用到的工具类,来自github.com/wuyouzhuguli

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

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

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }
    public static <T> T getBean(Class<T> clazz){
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }

    public static Class<?> getType(String name) {
        return applicationContext.getType(name);
    }
}
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: Java Springboot
最后更新:2020-11-27

hafuhafu

将思绪寄托于流逝而过的日子里。

点赞
< 上一篇
下一篇 >

文章评论

  • Airbo

    最近也是遇到了这个问题,网上内容有点少,看了一晚上才看到了这个文章。

    👍感谢博主,记录真是个好习惯。看博主最近都年更了,哈哈哈哈,还是要加油写博客的呀

    祝工作顺利

    2023-01-08
    回复
  • 取消回复

    hafuhafu

    将思绪寄托于流逝而过的日子里。

    COPYRIGHT © 2022 HafuHafu. ALL RIGHTS RESERVED.

    Theme Kratos Made By Seaton Jiang