为 @Inject 定义一个自定义的 InjectionResolver

Define a custom InjectionResolver for @Inject

我的目标是围绕系统注入解析器添加一些额外的逻辑(可以说是装饰它)。基本上,我想注册一个自定义注入解析器(例如描述 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);
        }
    });

到目前为止我尝试了什么:

有谁知道如何解决这个问题?

使用的版本:球衣 2.27

编辑:当我@Inject InjectionResolver 本身时,似乎 hk2 的 org.jvnet.hk2.internal.ThreeThirtyResolver 是为 org.glassfish.hk2.api.InjectionResolver 注入的,而我的自定义注入解析器是为 org.glassfish.jersey.internal.inject.InjectionResolver 注入的。但是,自定义注入解析器用于注入。

以下配置对我有用,感谢@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

}

为了注册解析器,我们将其绑定到正确的类型(我在球衣应用程序的 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 注释并围绕它编写一些自定义注入逻辑,可能使用默认系统注入解析器作为后备。