当management.port与服务器端口不同时,如何调用OncePerRequestFilter?

Don*_*mmy 2 java spring servlet-filters spring-boot spring-boot-actuator

我有一个可以延伸的过滤器OncePerRequestFilter。当我management.port=8081server.port=8080(或任何不同的端口)时,我的过滤器不会在任何 8081 URL 上调用。

在 8080 URL 上调用该过滤器。

如何让它在所有 URL 上调用,包括 8081 上的 URL?

筛选:

@Order( Ordered.LOWEST_PRECEDENCE )
public class TestFilter extends OncePerRequestFilter
{
    public TestFilter()
    {
        System.out.println( "Started" );
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException
    {
        System.out.println( "Checked should not filter" );
        return false;
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException
    {
        System.out.println( "Filtering" );

        // continue the processing
        filterChain.doFilter( request, response );
    }
}
Run Code Online (Sandbox Code Playgroud)

我通过以下方式添加它:

@Configuration
public class MyConfig
{
    @Bean
    public TestFilter testFilter()
    {
        return new TestFilter()
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑: 我尝试添加@ManagementContextConfiguration到我的配置类,但这也不起作用。

Don*_*mmy 6

尽管我无法找到文档,但答案似乎是执行以下所有操作:

  1. 添加一个带有注释的类@ManagementContextConfiguration
  2. 将该配置文件放在组件扫描之外(这样 Spring Boot 的正常自动配置将找不到它)
  3. 在 META-INF/spring.factories 中声明它:

META-INF/spring.factories:

在 spring-boot-2.0.0.RELEASE 之前:
org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration=com.packageoutsidescan.MyManagementFilterConfigurationClass

在 spring-boot-2.0.0.RELEASE (web子包)之后:

org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration=com.packageoutsidescan.MyManagementFilterConfigurationClass