在Spring Boot 1.4中不推荐使用FilterRegistrationBean。*

时间:2016-10-07 06:52:44

标签: java spring spring-mvc filter

我在项目中升级了Spring Boot依赖项,并且我意识到某些类(例如FilterRegistrationBean)已被弃用。

您知道如何在Spring Boot 1.4.1中实现过滤器吗?

过滤器之豆

@Bean
public FilterRegistrationBean filterRegistrationBean() {
    AuthenticationFilter f = new AuthenticationFilter();
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(f);
    registrationBean.addInitParameter("defaultToken", defaultToken);
    registrationBean.addInitParameter("secretKey", secretKey);
    ArrayList<String> match = new ArrayList<>();
    match.add("/users/*");
    registrationBean.setUrlPatterns(match);
    return registrationBean;
}

我的过滤器代码:

public class AuthenticationFilter implements Filter {

private String defaultToken;
private String secretKey;

private UserSessionTokenRepository userSessionTokenRepository;
private UserManager userManager;

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    defaultToken = filterConfig.getInitParameter("defaultToken");
    secretKey = filterConfig.getInitParameter("secretKey");
    userSessionTokenRepository = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext()).getBean(UserSessionTokenRepository.class);
    userManager = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext()).getBean(UserManager.class);
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    chain.doFilter(request, response);
}

public void addHeaders(HttpServletResponse response) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
}

public void destroy() {
}
}

2 个答案:

答案 0 :(得分:27)

答案 1 :(得分:5)

检查the javadoc。它刚刚移动到包org.springframework.boot.web.servlet