Jersey 2.26:定义自定义注入注释

时间:2018-03-16 10:05:13

标签: java dependency-injection jersey

我正在将一个JavaSE应用程序从Jersey 2.x迁移到2.26。该应用程序依赖于HK2进行依赖注入。

不幸的是,一些官方文档 - custom injection, chapter 23 - 现在不正确,尚未更新。在his answer here中,Paul解释了如何将HK2 Factory迁移到Supplier,现在该球衣用于设置自定义注射提供程序。效果很好,但我想在本章的其余部分寻求帮助:

如何设置自定义注入注释?

目前,我现有的自定义注入解析器类(完全按照文档编译)编译正常。我不确定他们是否应继续直接实施org.glassfish.hk2.api.InjectionResolver?在javadocs中,我找到InjectionResolverWrapper,我需要扩展它吗?

真正的问题是如何将注射旋转变压器绑定到自定义注射。这不编译:

            bind(SessionInjectResolver.class)
                .to(new TypeLiteral<InjectionResolver<SessionInject>>(){})
                .in(Singleton.class);

我非常感谢一个例子,如何在Jersey 2.26上再次使用自定义注释进行注入。

1 个答案:

答案 0 :(得分:3)

感谢Paul关于使用GenericType的评论,这里有一个解决方案再次适用于Jersey 2.26。它正在使用org.glassfish.hk2.api.*类。

<强> AbstractBinder

.... 

@Override
protected void configure() {
    /*
    Adds binding for @CurrentUser.
    By default, factories are being injected with PerLookup scope.
    */
    bindFactory(CurrentUserSupplier.class)
            .to(User.class)
            .proxy(true)
            .proxyForSameScope(false)
            .in(RequestScoped.class);
    bind(CurrentUserResolver.class)
            .to(new GenericType<InjectionResolver<CurrentUser>>(){})
            .in(Singleton.class);
}
....

<强> CurrentUserSupplier

public class CurrentUserSupplier implements Supplier<User> {

    // inject what is required

    @Override
    public User get() {
        // do what is necessary to obtain User
    // and return it
    }

}

<强> CurrentUserResolver

import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceHandle;

public class CurrentUserResolver implements InjectionResolver<CurrentUser> {

    @Inject
    @Named(InjectionResolver.SYSTEM_RESOLVER_NAME)
    InjectionResolver<Inject> systemInjectionResolver;

    @Override
    public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
        if (User.class == injectee.getRequiredType()) {
            return systemInjectionResolver.resolve(injectee, handle);
        }

        return null;
    }

    @Override
    public boolean isConstructorParameterIndicator() {
        return false;
    }

    @Override
    public boolean isMethodParameterIndicator() {
        return false;
    }
}