泽西岛 2.*.如何替换 Jersey 1.* 的 InjectableProvider 和 AbstractHttpContextInjectable [英] Jersey 2.*. How to replace InjectableProvider and AbstractHttpContextInjectable of Jersey 1.*
问题描述
我想创建一个类,其对象可以使用 @Context
注释(或者更好的自定义注释,用于需要将参数传递给注释的情况)注入到资源方法中.在 Jersey 1.* 我会使用 InjectableProvider
(在我的例子中与 AbstractHttpContextInjectable
一起使用).我想要实现的是类似于 @Auth
[1] 来自 dropwizard(使用 Jersey 1.7).
I would like to create a class whose objects can be injected using the @Context
annotation (or better yet a custom annotation for cases where I need to pass an argument to the annotation) into resource methods. In Jersey 1.* I would have used InjectableProvider
(in my case together with AbstractHttpContextInjectable
). What I'm trying to achieve is something like @Auth
[1] from dropwizard (which uses Jersey 1.7).
据我所知,Jersey 的注入功能已被 HK2 取代,我找不到我所描述的任何示例.
The injection capabilities of Jersey were replaced by HK2 as far as I know and I could not find any example of what I'm describing.
见这个问题 我在尝试遵循 Michal 指南时遇到的其他问题.
See this question for further problems I have encountered while trying to follow Michal's guide.
推荐答案
你需要实现InjectionResolver
You need to implement InjectionResolver<T> interface from HK2. Take a look at existing implementations that are present in Jersey workspace:
- ContextInjectionResolver 处理
@Context
- ParamInjectionResolver 处理
@PathParam
、@QueryParam
、...(通过它的子类) - AutowiredInjectResolver 处理
@Autowired
- ContextInjectionResolver handling
@Context
- ParamInjectionResolver handling
@PathParam
,@QueryParam
, ... (via it's subclasses) - AutowiredInjectResolver handling
@Autowired
一旦你有了这个,你需要扩展来自HK2的>AbstractBinder并通过它的#configure()
方法绑定你的InjectionResolver
:
Once you have this, you need to extend AbstractBinder from HK2 and bind your InjectionResolver
via it's #configure()
method:
public class MyResolverBinder extends AbstractBinder {
@Override
protected void configure() {
bind(MyInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<MyAnnotation>>() {})
.in(Singleton.class);
}
}
... 并在您的应用程序类中注册此绑定器的实例(或通过 功能):
... and register an instance of this binder in your application class (or via feature):
功能
:
public class MyFeature implements Feature {
@Override
public boolean configure(final FeatureContext context) {
context.register(new MyResolverBinder());
return true;
}
}
注册MyFeature
到Application
:
public class JaxRsApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
final HashSet<Class<?>> classes = new HashSet<Class<?>>();
classes.add(MyFeature.class);
// Register other providers or resources.
return classes;
}
}
在ResourceConfig
new ResourceConfig()
// Register either MyFeature
.register(MyFeature.class)
// or MyResolverBinder
.register(new MyResolverBinder())
// Register other providers or resources
.packages("my.package");
这篇关于泽西岛 2.*.如何替换 Jersey 1.* 的 InjectableProvider 和 AbstractHttpContextInjectable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!