您好,登錄后才能下訂單哦!
Springboot @WebFilter無法注入其他Bean的示例分析,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
示例問題代碼:
@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); } }
現(xiàn)象:
本地運(yùn)行測試均可通過,上測試環(huán)境后運(yùn)行注入bean為空
現(xiàn)象:使用外置tomcat可觸發(fā),本地使用內(nèi)置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”})
看完上述內(nèi)容,你們掌握Springboot @WebFilter無法注入其他Bean的示例分析的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。