Han*_*ank 4 java dependency-injection jersey
我正在将一个 JavaSE 应用程序从 Jersey 2.x 迁移到 2.26。该应用程序依赖 HK2 进行依赖注入。
不幸的是,一些官方文档 -自定义注入,第 23 章- 现在不正确并且尚未更新。在他的回答中,Paul 解释了如何将 HK2 迁移Factory到Supplier,jersey 现在使用它来设置自定义注入提供程序。效果很好,但我想为本章的其余部分寻求帮助:
如何设置自定义注入注释?
目前,我现有的自定义注入解析器类(完全按照文档)编译得很好。我不确定他们是否应该继续直接实施org.glassfish.hk2.api.InjectionResolver?在 javadocs 中,我找到了InjectionResolverWrapper,我需要扩展它吗?
真正的问题是如何将注入解析器绑定到自定义注入。这不编译:
bind(SessionInjectResolver.class)
.to(new TypeLiteral<InjectionResolver<SessionInject>>(){})
.in(Singleton.class);
Run Code Online (Sandbox Code Playgroud)
我非常感谢如何使用自定义注释进行注入再次在 Jersey 2.26 上工作的示例。
感谢 Paul 关于使用的评论GenericType,这里有一个在 Jersey 2.26 上再次适用于我的解决方案。它正在使用org.glassfish.hk2.api.*类。
抽象活页夹
....
@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);
}
....
Run Code Online (Sandbox Code Playgroud)
当前用户供应商
public class CurrentUserSupplier implements Supplier<User> {
// inject what is required
@Override
public User get() {
// do what is necessary to obtain User
// and return it
}
}
Run Code Online (Sandbox Code Playgroud)
当前用户解析器
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
823 次 |
| 最近记录: |