Java Jersey 2中的两个自定义注入注释
我应该如何进行ValueFactoryProvider绑定以使Jersey 2中的两个自定义注入注释共存?下面我提供了一个当前方法的示例,正如您所看到的,Hello注释注入“隐藏”了SmallTalk注释注入 您好注释:Java Jersey 2中的两个自定义注入注释,java,annotations,jersey,inject,hk2,Java,Annotations,Jersey,Inject,Hk2,我应该如何进行ValueFactoryProvider绑定以使Jersey 2中的两个自定义注入注释共存?下面我提供了一个当前方法的示例,正如您所看到的,Hello注释注入“隐藏”了SmallTalk注释注入 您好注释: @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) public @interface Hello { } @Retention(RetentionPolicy.RUNTIME) @Targ
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface Hello {
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface SmallTalk {
}
SmallTalk注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface Hello {
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface SmallTalk {
}
Hello注释解析程序:
@Singleton
public class HelloResolver {
public static class HelloInjectionResolver extends ParamInjectionResolver<Hello> {
public HelloInjectionResolver() {
super(HelloValueFactoryProvider.class);
}
}
@Singleton
public static class HelloValueFactoryProvider extends AbstractValueFactoryProvider {
@Inject
public HelloValueFactoryProvider(final MultivaluedParameterExtractorProvider extractorProvider,
final ServiceLocator injector) {
super(extractorProvider, injector, UNKNOWN);
}
@Override
protected Factory<?> createValueFactory(final Parameter parameter) {
final Class<?> classType = parameter.getRawType();
if (classType == null || (!classType.equals(String.class))) return null;
return new AbstractContainerRequestValueFactory<String>() {
@Override
public String provide() {
return "Hello!";
}
};
}
}
public static class Binder extends AbstractBinder {
@Override
protected void configure() {
bind(HelloValueFactoryProvider.class).to(ValueFactoryProvider.class).in(Singleton.class);
bind(HelloInjectionResolver.class).to(
new TypeLiteral<InjectionResolver<Hello>>() {
}
).in(Singleton.class);
}
}
}
使用两种注入注释的资源:
@Path("/")
public class HelloResource {
@GET
@Path("hello")
@Produces("application/json")
public String hello(@Hello final String hello, @SmallTalk final String smallTalk) {
return hello + " " + smallTalk;
}
}
请求资源时的结果-应该是“你好!天气真好。”:
找到了解决方案!我补充说
if (parameter.getAnnotation(Hello.class) == null) return null;
及
两个价值工厂提供者的
createValueFactory
方法。这对我来说也很有效,但看起来很不雅观。一定有更好的办法。您找到一个了吗,@Stine?一个稍微好一点的解决方案是parameter.getSourceAnnotation()instanceof Hello。我知道,不是更好,但至少方法似乎是为了检查触发注入的注释。
if (parameter.getAnnotation(SmallTalk.class) == null) return null;