我的目标是在System Injection Resolver周围添加一些其他逻辑(可以修饰它)。基本上,我想注册一个自定义注入解析器(例如描述的here),但要注册javax.inject.@Inject
注释。如果创建其他自定义批注,则该设置有效,但使用@Inject时则无效。我的实现如下:
注入解析器:
@Singleton
@Rank(Integer.MAX_VALUE)
public class InjectInjectionResolver
implements InjectionResolver<Inject> {
private final InjectionResolver<Inject> injectionResolver;
@Inject
public InjectInjectionResolver(
@Named(InjectionResolver.SYSTEM_RESOLVER_NAME) final InjectionResolver<Inject> injectionResolver) {
this.injectionResolver = injectionResolver;
}
@Override
public Object resolve(final Injectee injectee, final ServiceHandle<?> root) {
throw new RuntimeException("Why is this never called?");
}
@Override
public boolean isConstructorParameterIndicator() {
return injectionResolver.isConstructorParameterIndicator();
}
@Override
public boolean isMethodParameterIndicator() {
return injectionResolver.isMethodParameterIndicator();
}
}
然后我在ResourceConfig
内部注册解析器:
register(new AbstractBinder() {
@Override
protected void configure() {
bind(InjectInjectionResolver.class).to(new GenericType<InjectionResolver<Inject>>() {}).in(Singleton.class);
}
});
到目前为止我尝试过的事情:
@Rank
org.glassfish.jersey.internal.inject.AbstractBinder
或org.glassfish.hk2.utilities.binding.AbstractBinder
与TypeLiteral
一起使用,并实现org.glassfish.hk2.api.InjectionResolver
或org.glassfish.jersey.internal.inject.InjectionResolver
有人知道如何解决这个问题吗?
使用的版本:球衣2.27
编辑:当我@InjectionInjectionResolver本身时,似乎为org.jvnet.hk2.internal.ThreeThirtyResolver
注入了hk2的org.glassfish.hk2.api.InjectionResolver
,而我的自定义注入解析器也为org.glassfish.jersey.internal.inject.InjectionResolver
注入了。但是,自定义注入解析器不用于注入。
答案 0 :(得分:0)
由于@ jwells131313使我重回正轨,以下配置对我有用。我尝试使用完全限定的名称,否则可能来自javax.inject.*
包。
@Singleton
@Rank(Integer.MAX_VALUE)
@org.jvnet.hk2.annotations.Service
public class MyHk2InjectionResolver
implements org.glassfish.hk2.api.InjectionResolver<Inject> {
private final org.glassfish.hk2.api.InjectionResolver<Inject> injectionResolver;
@Inject
public MyHk2InjectionResolver(
@Named(org.glassfish.hk2.api.InjectionResolver.SYSTEM_RESOLVER_NAME) final org.glassfish.hk2.api.InjectionResolver<Inject> injectionResolver) {
this.injectionResolver = injectionResolver;
}
// ... required methods, could just delegate to system resolver
}
要注册解析器,我们将其绑定到正确的类型(我在jersey应用程序的ResourceConfig中进行解析):
register(new org.glassfish.hk2.utilities.binding.AbstractBinder() {
@Override
protected void configure() {
bind(MyHk2InjectionResolver.class)
.to(new org.glassfish.hk2.api.TypeLiteral<org.glassfish.hk2.api.InjectionResolver<Inject>>() {})
.in(Singleton.class);
}
});
使用此设置,您可以继续使用@Inject
批注并在其周围编写一些自定义注入逻辑,可能使用默认的系统注入解析器作为后备。