【发布时间】:2017-11-03 10:43:19
【问题描述】:
我正在尝试在我的主 Spring Boot 项目的单独 jar 中创建过滤器。其中之一是 Actuator 中的 Trace 过滤器(调用 /trace 时执行的过滤器),我将其配置为不跟踪对 /trace 本身的调用。如果我在项目中定义过滤器,它会完美运行,并且不会跟踪对 /trace 的调用。
但是,当我将该类提取到另一个库并从主项目中引用它时,它会跟踪这些调用。我检查了所有引用是否正确,并且正在执行过滤器。但是,我怀疑在初始化依赖项时,我的过滤器和 WebRequestTraceFilter(我的过滤器中的类正在继承)都被实例化了。这是过滤器类:
package common.api.filters.trace;
import org.springframework.boot.actuate.trace.TraceProperties;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.boot.actuate.trace.WebRequestTraceFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* Class to exclude some some endpoints to be traced such as /admin/**, * /trace and
* endpoints provide static files like /css/** and /js/**.
*/
@Component
public class RequestTraceFilter extends WebRequestTraceFilter {
private static final String[] excludedEndpoints = new String[]{"/css/**", "/js/**", "/trace"};
public RequestTraceFilter(TraceRepository repository, TraceProperties properties) {
super(repository, properties);
}
/*
The default implementation was always returning false.
With this implementation, it returns true for the endpoints we don’t want to trace.
*/
@Override
protected boolean shouldNotFilter(final HttpServletRequest request) throws ServletException {
return Arrays
.stream(excludedEndpoints)
.anyMatch(e -> new AntPathMatcher().match(e, request.getServletPath()));
}
}
我也尝试过删除标签@Component,并在一个带有@Configuration标签的类中以这种方式初始化过滤器:
@Bean
public FilterRegistrationBean createTraceFilter(){
FilterRegistrationBean frb = new FilterRegistrationBean();
frb.setFilter(new RequestTraceFilter(new InMemoryTraceRepository(), new TraceProperties()));
return frb;
}
但结果是一样的:正在执行过滤器,但正在跟踪对 /trace 的调用。
如何将主项目中的过滤器初始化为跟踪时唯一执行的过滤器?
【问题讨论】:
标签: java filter trace spring-boot-actuator