欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-04 15:01:06
示例问题代码:@webfilter(filtername = "authorizefilter", urlpatterns = {"*.htm", "*.html"}, asyncsupported...

示例问题代码:

@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的示例问题的文章就介绍到这了,更多相关springboot 无法注入bean内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!