过滤器手动注入Service Bean方法

  @Override
    public void init(FilterConfig arg0) throws ServletException {
        ServletContext servletContext = arg0.getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(servletContext);
        if(cxt != null && cxt.getBean("serviceClass") != null && serviceClass == null) {
            serviceClass = (ServiceClass) cxt.getBean("serviceClass");
        }
    }

   首先在Filter实现过滤器类中声明将要注入的Service对象。在过滤器初始化init()方法中,通过FilterConfig文件获取上下文对象。调用Spring中WebApplicationContextUtils通过get方法获取XmlWebApplicationContext对象,调用getBean()即可。

原文地址:https://www.cnblogs.com/fantastic-clouds/p/8398471.html