Java 拦截器中@Autowired 为空问题解决

字数 0阅读 12
public class ResponseFilter implements Filter{

    @Autowired
    private PropertiesConfig propertiesConfig;


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {

        // 解决 @Autowired 为 null 问题
        if(propertiesConfig==null){
            ServletContext servletContext = request.getServletContext();
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            propertiesConfig = webApplicationContext.getBean(PropertiesConfig.class);
        }

        HttpServletRequest req = (HttpServletRequest)request;
        // 使用我们自定义的响应包装器来包装原始的ServletResponse
        ResponseWrapper wrapper = new ResponseWrapper((HttpServletResponse) response);
        // 这句话非常重要,注意看到第二个参数是我们的包装器而不是response
        filterChain.doFilter(request, wrapper);
        // 获取到我们所截获的值 --> 做处理之前所获取到的值
        String result = wrapper.getResult();

        // 输出最终的结果 --> 做完处理之后再把这个值返回回去
        response.getOutputStream().write(responseStr.getBytes());

    }

    @Override
    public void init(FilterConfig arg0)
            throws ServletException {
    }

    @Override
    public void destroy() {
    }
}

推荐阅读更多精彩内容