服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Springboot @WebFilter无法注入其他Bean的示例问题

Springboot @WebFilter无法注入其他Bean的示例问题

2021-12-27 14:26954L Java教程

这篇文章主要介绍了Springboot @WebFilter无法注入其他Bean的示例问题,本文通过示例代码给大家分享解决方法,需要的朋友可以参考下

示例问题代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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则无此问题

解决代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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);
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@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的示例问题的文章就介绍到这了,更多相关Springboot 无法注入Bean内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/wkh___/article/details/120221831

延伸 · 阅读

精彩推荐