spring Filter 中使用@Autowired 方法

ServletContext,是一个全局的储存信息的空间,服务器开始建立,服务器关闭销毁。
request,每次请求一个;
session,一个会话一个;
servletContext,所有用户共用一个。
ServletContext维护着一个服务器中的一个特定URL名字空间(比如,/myapplication)下的所有Servlet,Filter,JSP,JavaBean等Web部件的集合。也就是说Servlet和Filter并不是由Spring ApplicationContext维护的,所以使用@Autowired注解在调用时会NPE。

方法一

在filter类init中强制注册@Autowired

override fun init(filterConfig: FilterConfig?) {
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig?.servletContext)
}

方法二,不能直接使用@Autowired

在主类中加载

@Import(WebApplicationContextHolder::class)
class WebApplicationContextHolder : ServletContextInitializer {
    companion object {
        
        var currentWebApplicationContext: WebApplicationContext? = null
            private set
    }
    
    /**
     * 在启动时将servletContext 获取出来,后面再读取二次使用。
     
     * @param servletContext
     * *
     * *
     * @throws ServletException
     */
    @Throws(ServletException::class)
    override fun onStartup(servletContext: ServletContext) {
        currentWebApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext)
    }
}

filter中 将想要注解的bean拿到

//先定义,在init中赋值
var appService:ExternalAppService?=null

·······
    override fun init(filterConfig: FilterConfig?) {
//      SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig?.servletContext)
        appService=WebApplicationContextHolder.currentWebApplicationContext?.getBean(ExternalAppService::class.java)
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,058评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,422评论 19 139
  • 这部分主要是与Java Web和Web Service相关的面试题。 96、阐述Servlet和CGI的区别? 答...
    杂货铺老板阅读 5,238评论 0 10
  • 什么是Spring Spring是一个开源的Java EE开发框架。Spring框架的核心功能可以应用在任何Jav...
    jemmm阅读 16,661评论 1 133
  • 半根烟,伴世安。思想不在落寞,灵魂有地安落。一杯酒,言豪放。外面世界酒中言,内心世界坦荡荡。唯有破烂不堪、荒唐无际...
    王益鑫阅读 3,184评论 0 0