@Context注入适用于类,但不能使它与Objects一起使用。
ContainerRequestFilter中的httpServletRequest生成空指针。
Dropwizard版本: - 1.1.0
ContainerRequestFilter
public class ApplicationIPAuthFilter implements ContainerRequestFilter { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationIPAuthFilter.class); private HerculesRestAccessor restAccessor; private String applicationName; @Context private HttpServletRequest httpServletRequest; public ApplicationIPAuthFilter(){ } public ApplicationIPAuthFilter(HerculesRestAccessor accessor, String applicationName) { restAccessor = accessor; this.applicationName = applicationName; } @Override public void filter(ContainerRequestContext requestContext) throws IOException { // need remote Ip String remoteIp = this.httpServletRequest.getRemoteAddr(); .... } }
DynamicFeature
@Provider public class ApplicationIPAuthFeature implements DynamicFeature { private final HerculesRestAccessor accessor; private final String applicationName; public ApplicationIPAuthFeature(HerculesRestAccessor accessor, String applicationName) { this.accessor = accessor; this.applicationName = applicationName; } @Override public void configure(ResourceInfo resourceInfo, FeatureContext context) { if (resourceInfo.getResourceMethod().getAnnotation(ApplicationIPAuthRequired.class) != null) { // not working context.register(new ApplicationIPAuthFilter(accessor, applicationName)); //@Context injection works in ContainerRequestFilter for classes //context.register(ApplicationIPAuthFilter.class); } } }
我试图在ContainerRequestFilter中获取远程ip,以基于ip验证请求。
如何解决这个问题..需要帮助吗?
答案 0 :(得分:4)
It's a known issue with DynamicFeature。注册作为对象时,注射不起作用。
您可以做的一件事就是手动注入它,就像this post中提到的那样。
您可以做的另一件事是使HerculesRestAccessor
和applicationName
注射。或者更确切地说,使应用程序名称可注入,您可以将其设置为配置属性inject the configuration。如果这样做,那么您可以将过滤器注册为一个类,并且所有注入都应该有效。