@Context injection not working in Jersey ContainerRequestFilter (Dropwizard)

ⅰ亾dé卋堺 提交于 2019-12-13 13:28:23

问题


@Context injection works with classes but not able to make it work with Objects.

httpServletRequest in ContainerRequestFilter produces null pointer.

Dropwizard Version:- 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);
        }
    }
}

I'm trying to fetch remote ip in ContainerRequestFilter to authenticate request based on ip.

How do I fix this.. need help?


回答1:


It's a known issue with DynamicFeature. Injections don't work when registering as an object.

One thing you can do is manually inject it, like mentioned in this post.

Another thing you can do is make the HerculesRestAccessor and the applicationName injectable. Or rather then making the application name injectable, you can make it a configuration property and inject the configuration. If you do this, then you can register the filter as a class, and all the injections should work.



来源:https://stackoverflow.com/questions/44097938/context-injection-not-working-in-jersey-containerrequestfilter-dropwizard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!