美文网首页
spring Filter 中使用@Autowired 方法

spring Filter 中使用@Autowired 方法

作者: 大罗马的太阳 | 来源:发表于2017-03-01 22:43 被阅读1606次

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 Filter 中使用@Autowired 方法

      本文链接:https://www.haomeiwen.com/subject/ougcgttx.html