您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。