亲宝软件园·资讯

展开

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

954L 人气:0
想了解Springboot @WebFilter无法注入其他Bean的示例问题的相关内容吗,954L在本文为您仔细讲解Springboot 无法注入Bean的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Springboot,@WebFilter,Bean,Springboot,无法注入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”})

加载全部内容

相关教程
猜你喜欢
用户评论