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 public 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”})
看完上述内容,你们掌握Springboot @WebFilter无法注入其他Bean的示例分析的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。