[英]Java EE - How to inject method parameter on method with custom annotation
假設我在Java EE / EJB / JAX-RS中有以下代碼:
@POST
@Path("some/path")
@MyAnnotation
public MyResponse createActivation(MyRequest request, CustomValue value) {
// ...
}
我如何檢查自定義@MyAnnotation
批注的存在,並在存在批注的情況下根據一些請求上下文參數填充CustomValue value
方法參數?
注意:我已經在Spring中使用HandlerInterceptorAdapter
和HandlerMethodArgumentResolver
編寫了這段代碼。 現在我需要在沒有Spring的情況下做同樣的事情。 我已經發現了ContainerRequestFilter
並使用它來檢查注解,但是現在我正努力注入方法參數。
自定義方法參數注入的處理方式與常規(即字段,構造函數)注入方式略有不同。 對於Jersey,這需要實現ValueFactoryProvider
。 對於您的情況,它看起來像
public class MyAnnotationParamValueProvider implements ValueFactoryProvider {
@Inject
private ServiceLocator locator;
@Override
public Factory<?> getValueFactory(Parameter parameter) {
if (parameter.getAnnotation(MyAnnotation.class) != null
&& parameter.getRawType() == CustomValue.class) {
final Factory<CustomValue> factory
= new AbstractContainerRequestValueFactory<CustomValue>() {
@Override
public CustomValue provide() {
final ContainerRequest request = getContainerRequest();
final String value = request.getHeaderString("X-Value");
return new CustomValue(value);
}
};
locator.inject(factory);
return factory;
}
return null;
}
@Override
public PriorityType getPriority() {
return Priority.NORMAL;
}
}
然后,您需要向ResourceConfig
注冊它
public class AppConfig extends ResourceConfig {
public AppConfig() {
register(new AbstractBinder() {
@Override
protected void configure() {
bind(MyAnnotationParamValueProvider.class)
.to(ValueFactoryProvider.class)
.in(Singleton.class);
}
});
}
}
請參閱此要點中的完整示例
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.