在Filter 中注入 Service

贴一段代码简单明了:

@WebFilter(filterName = "MainFilter",urlPatterns = "/*")
public class MainFilter implements Filter {

    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(filterConfig.getServletContext());
        userService = ctx.getBean(UserService.class);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
           filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

就这样,userService就可以正常使用了

11 thoughts on “在Filter 中注入 Service

发表评论

电子邮件地址不会被公开。 必填项已用*标注