球衣 2.*.如何替换 InjectableProvider 和 AbstractHttpContextInjectable of Jersey 1.*
2022-09-02 10:06:48
您需要从 HK2 实现 InjectionResolver<T> 接口。查看泽西工作区中存在的现有实现:
@Context
@PathParam
@QueryParam
@Autowired
一旦你有了这个,你需要从HK2扩展抽象Binder,并通过它的方法绑定你的:InjectionResolver
#configure()
public class MyResolverBinder extends AbstractBinder {
@Override
protected void configure() {
bind(MyInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<MyAnnotation>>() {})
.in(Singleton.class);
}
}
...并在应用程序类中注册此绑定程序的实例(或通过功能):
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;
}
}
注册或在MyResolverBinder
Feature
ResourceConfig
new ResourceConfig()
// Register either MyFeature
.register(MyFeature.class)
// or MyResolverBinder
.register(new MyResolverBinder())
// Register other providers or resources
.packages("my.package");
提供 的实现仅有助于注入,而在解析资源方法参数的值时则不然。InjectionResolver
至少在泽西岛 2.11 中,您需要定义一个带有 .ValueFactoryProvider
@Provider
@Provider
public class MyValueFactoryProvider implements ValueFactoryProvider {
@Inject
private MyFactory factory;
@Override
public Factory<?> getValueFactory(Parameter parameter) {
if (parameter.getAnnotation(MyAnnotationParam.class) != null) {
return factory;
}
return null;
}
@Override
public PriorityType getPriority() {
return Priority.NORMAL;
}
}
如果您还想获取注入的值,例如,成员和构造函数参数,那么 InjectionResolver 可以很好地工作。