在Jersey 2.27中注册自定义ValueParamProvider [英] Registering a custom ValueParamProvider in Jersey 2.27

查看:215
本文介绍了在Jersey 2.27中注册自定义ValueParamProvider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这些是内部API,但是如果内部可以使用它们,为什么不让特权较低的人群使用它们,它们也非常有用.即使这些API在Jersey 2.25中是内置的,也可以使用,并且我想在不破坏自定义Jersey扩展的情况下升级Jersey版本.

I realize that these are internal APIs, but if they're available internally why not make them usable by the less privileged masses, and they're also extremely useful. Even though these APIs were internal in Jersey 2.25 they could be used, and I'd like to upgrade my Jersey version without breaking my custom Jersey extensions.

当然可以扩展

It's certainly possible to extend ValueParamProvider in Jersey 2.27, but I no longer see a way to register that Provider along with it's triggering annotation. Looking at how Jersey does this for its own implementations, it now uses a BoostrapConfigurator, which seems to be internalized to such an extent that external implementations can't use the same methodology.

也许我错了,如果有人对方法有清晰的描述,那就太好了.否则,有人知道做相同事情的方法吗?

Maybe I'm wrong about that, and if someone has a clear description of how, that would be great. Otherwise, does anyone know of a method for doing the same thing?

用于可以正常工作...

This used to work...

ResourceConfig resourcceConfig = ...

resourceConfig.register(new AbstractBinder() {

    @Override
    protected void configure (){ 
      bind(MyParamValueFactoryProvider.class).to(ValueFactoryProvider.class).in(Singleton.class);
      bind(MyParamInjectionResolver.class).to(new TypeLiteral<InjectionResolver<EntityParam>>() {

      }).in(Singleton.class);
    }
  }
});

使用AbstractValueFactoryProviderParamInjectionResolver的适当实现.

现在看来您需要实现ValueParamProvider,这很容易,但是我不确定如何再使用Jersey框架正确注册它.任何帮助表示赞赏.

Now it looks like you need to implement ValueParamProvider, which is easy enough, but I'm not sure how to register that properly with the Jersey framework anymore. Any help appreciated.

推荐答案

您不需要使用任何BootstrapConfigurator.您需要做的就是将服务添加到注入器并

You don't need to use any BootstrapConfigurator. All you need to is add the services to the injector and they will be added later to the list of value providers.

要配置它,您仍然可以使用AbstractBinder,但是可以使用

To configure it, you can still use the AbstractBinder, but instead of the HK2 one, use the Jersey one. The ValueParamProvider can still be bound the same way, but for the InjectionResolver, you should make sure to implement not the HK2 resolver, but the Jersey one. Then instead of binding to TypeLiteral, bind to GenericType.

我只是想补充一点,人们在尝试实现参数注入时会误解是,我们还需要InjectResolver来为方法参数使用自定义注释.不是这种情况.方法参数注释只是一个标记注释,我们应该在ValueParamProvider#getValueProvider()方法内部进行检查.仅对于非方法参数注入(例如,字段和构造函数注入)才需要InjectResolver.如果不需要,则不需要InjectionResolver.

I just want to add that a misconception that people have when trying to implement parameter injection is that we also need an InjectResolver to use a custom annotation for the method parameter. This is not the case. The method parameter annotation is just a marker annotation that we should check inside ValueParamProvider#getValueProvider() method. An InjectResolver is only needed for non-method-parameter injections, for instance field and constructor injection. If you don't need that, then you don't need the InjectionResolver.

以下是使用 Jersey测试框架的完整示例.我没有使用InjectionResolver只是为了表明它不是必需的.

Below is a complete example using Jersey Test Framework. I didn't use an InjectionResolver, just to show that it's not needed.

import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.spi.internal.ValueParamProvider;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;

import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.core.Response;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.Function;

import static org.assertj.core.api.Assertions.assertThat;


public class ParamInjectTest extends JerseyTest {

    @Target({ElementType.PARAMETER, ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Auth {
    }

    private static class User {
        private String username;
        public User(String username) {
            this.username = username;
        }
        public String getUsername() {
            return this.username;
        }
    }

    public static class AuthValueParamProvider implements ValueParamProvider {

        @Override
        public Function<ContainerRequest, ?> getValueProvider(Parameter parameter) {
            if (parameter.getRawType().equals(User.class)
                    && parameter.isAnnotationPresent(Auth.class)) {
                return new UserParamProvider();
            }
            return null;
        }

        private class UserParamProvider implements Function<ContainerRequest, User> {
            @Override
            public User apply(ContainerRequest containerRequest) {
                return new User("Peeskillet");
            }
        }

        @Override
        public PriorityType getPriority() {
            return Priority.HIGH;
        }
    }

    public static class AuthFeature implements Feature {

        @Override
        public boolean configure(FeatureContext context) {
            context.register(new AbstractBinder() {
                @Override
                protected void configure() {
                    bind(AuthValueParamProvider.class)
                            .to(ValueParamProvider.class)
                            .in(Singleton.class);
                }
            });

            return true;
        }
    }

    @Path("test")
    @Consumes("text/plain")
    public static class TestResource {
        @POST
        @Produces("text/plain")
        public Response post(String text, @Auth User user) {
            return Response.ok(user.getUsername() + ":" + text).build();
        }
    }


    @Override
    public ResourceConfig configure() {
        return new ResourceConfig()
                .register(TestResource.class)
                .register(AuthFeature.class);
    }

    @Test
    public void testIt() {
        final Response response  = target("test")
                .request()
                .post(Entity.text("Test"));

        assertThat(response.getStatus()).isEqualTo(200);
        assertThat(response.readEntity(String.class)).isEqualTo("Peeskillet:Test");
    }
}


我要提到的另一件事是,在以前的版本中,您扩展了AbstractValueFactoryProvider并实现了ParamInjectionResolver,大多数人这样做是为了遵循Jersey如何实现参数注入,同时仍然允许其他注入点(字段和构造函数) .如果您仍想使用此模式,则可以.


Another thing I'll mention is that in previous versions where you extended AbstractValueFactoryProvider and implemented a ParamInjectionResolver, most people did this to follow how Jersey implemented parameter injection while still allowing for other injection points (field and constructor). If you still want to use this pattern, you can.

下面是重构的上述测试中的AuthFeature

Below is the AuthFeature from the above test refactored

public static class AuthFeature implements Feature {

    @Override
    public boolean configure(FeatureContext context) {
        InjectionManager im = InjectionManagerProvider.getInjectionManager(context);

        AuthValueParamProvider authProvider = new AuthValueParamProvider();

        im.register(Bindings.service(authProvider).to(ValueParamProvider.class));

        Provider<ContainerRequest> request = () -> {
            RequestProcessingContextReference reference = im.getInstance(RequestProcessingContextReference.class);
            return reference.get().request();
        };

        im.register(Bindings.injectionResolver(new ParamInjectionResolver<>(authProvider, Auth.class, request)));

        return true;
    }
}

我只是从源头中找出这些东西.我在

I figured this stuff out just digging through the source. All this configuration I saw in the ValueParamProviderConfigurator. You don't need to implement your own ParamInjectionResolver. Jersey has a concrete class already that we can just use, as done in the feature above.

如果您将TestResource更改为按字段注入,则它应该可以正常工作

If you change the TestResource to inject by field, it should work now

@Path("test")
@Consumes("text/plain")
public static class TestResource {

    @Auth User user;

    @POST
    @Produces("text/plain")
    public Response post(String text) {
        return Response.ok(user.getUsername() + ":" + text).build();
    }
}

这篇关于在Jersey 2.27中注册自定义ValueParamProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆