我正在创建一个Servlet过滤器作为一个独立的jar(使用brave作为spring sleuth-Greenwich.BUILD-SNAPSHOT的一部分),以便可以在Spring boot应用中使用它。我创建了一个过滤器,并将其包含在我的Spring Boot应用程序中。但是这样做时,它总是返回空指针异常(尽管它在zipkin服务器中创建了一个半烘烤的跨度),如下所示:
package com.somepackage;
import brave.ScopedSpan;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
public class TestFilter implements Filter {
@Autowired
private Tracer tracer;
@Autowired
Span span;
@Autowired
private Tracing tracing;
FilterConfig filterConfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String contextPath = httpServletRequest.getServletPath();
StringBuffer requestUrl = httpServletRequest.getRequestURL();
//always return null pointer at the below line 1. ??
Span span = tracer.newTrace().name("some-span-name").start(); //line 1
try {
span.tag("context-path", contextPath);
String logId = MDC.get(LOG_ID); //Assuming a key in MDC
span.tag("LOG_ID", correlationId);
span.tag("ENV", "dev");
chain.doFilter(request, response);
} catch (RuntimeException | Error e) {
span.error(e);
throw e;
} finally {
span.finish(); // always finish the span
}
}
}
@Override
public void destroy() {}
}
{"thread":"http-nio-8080-exec-2","level":"ERROR","loggerName":"org.springframework.cloud.sleuth.instrument.web.ExceptionLoggingFilter","message":"Uncaught exception thrown","thrown":{"commonElementCount":0,"name":"java.lang.NullPointerException","extendedStackTrace":[{"class":"com.somepackage.TestFilter","method":"doFilter","file":"EmZipkinFilter.java","line":37,"exact":false,"location":"testzipkin-1.0-SNAPSHOT.jar!/","version":"?"}