本文主要是介绍SpringBoot无法扫描到@Configuration注解的Filter过滤器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
SpringBoot的优点,就是整合了所有框架,便于快速开发,其他的就不多说了。在SpirngBoot工程中,过滤器Filter是经常使用的,下面先介绍一下过滤器的配置方法。
第一种方法:@WebFilter注解方式
使用@WebFilter注解为声明当前类为filter,第一个参数为该filter起一个名字,第二个参数为说明要拦截的请求地址,当前类需要实现Filter接口,里面有三个方法,分别为过滤器初始化、过滤方法和过滤器销毁。
@WebFilter(filterName = "myFilter1", urlPatterns = "/*")
public class MyFilter1 implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("进入过滤器初始化方法");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {log.info("myFilter1 begin");try {System.out.println("进入过滤器业务逻辑方法");chain.doFilter(request, response);} catch (Exception e) {log.error("error!", e);}log.info("myFilter1 end");}@Overridepublic void destroy() {System.out.println("进入过滤器销毁方法");}
}
在SpringBoot启动类上加上以下注解
@ServletComponentScan注解,@ServletComponentScan注解所扫描的包路径必须包含该Filter
例如:
@SpringBootApplication
@ServletComponentScan(basePackages = "com.example.demo.filter")
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
第二种方法:@Bean注解方式
MyFilter.java类,不要加注解@WebFilter,代码如下:
public class MyFilter implements Filter {@Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)throws IOException, ServletException {// TODO Auto-generated method stubHttpServletRequest request = (HttpServletRequest) srequest;System.out.println("this is MyFilter,url :"+request.getRequestURI());srequest.setCharacterEncoding("UTF-8");sresponse.setContentType("text/html;chartset=UTF-8");filterChain.doFilter(srequest, sresponse);}@Overridepublic void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stub}}
新建配置类WebConfiguration.java,配置bean,代码如下:
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter{@Beanpublic RemoteIpFilter remoteIpFilter() {return new RemoteIpFilter();}@Beanpublic FilterRegistrationBean testFilterRegistration() {FilterRegistrationBean registration = new FilterRegistrationBean();registration.setFilter( MyFilter());registration.addUrlPatterns("/*");/*registration.addInitParameter("paramName", "paramValue");*/registration.setName("MyFilter");registration.setOrder(1);return registration;}}
然后就可以启动,查看运行效果
遇到的问题:SpringBoot启动时,无法加载到配置的Filter过滤器
原因分析:确认启动类和config的包是否在同一级目录下
正确目录结构为:
欢迎关注以下公众号进行交流:
这篇关于SpringBoot无法扫描到@Configuration注解的Filter过滤器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!