洞察探讨小游戏SDK接入的最佳实践以及对企业跨平台开发的优势
879
2022-12-09
Springboot @WebFilter无法注入其他Bean的示例问题
示例问题代码:
@WebFilter(filterName = "authorizeFilter", urlPatterns = {"*.htm", "*.html"}, asyncSupported = true)
public class AuthorizeFilter implements Filter {
@Autowired
private OtherBean otherBean;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// true
System.out.println(otherBean == null);
}
}
现象:
本地运行测试均可通过,上测试环境后运行注入bean为空
现象:使用外置tomcat可触发,本地使用内置tomcat则无此问题
解决代码
@Component
public class AuthorizeFilter implements Filter {
@Autowired
private OtherBean otherBean;
@Override
publihttp://c void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// false
System.out.println(otherBean == null);
}
}
@Configuration
public class WebFilterConfig implements WebMvcConfigurer {
@Autowired
private AuthorizeFilter authorizeFilter;
@Bean("authorizeFilterBean")
public FilterRegistrationBean authorizeFilterBean() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(authorizeFilter);
registration.addUrlPatterns(new String[]{"*.htm", "*.html"});
registration.setName("authorizeFilter");
registration.setAsyncSupported(true);
return registration;
}
}
启动类加上:@ServletComponentScan({“com.hybase.site.filter”})
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~