我有一个拦截器绑定,它是参数化的:
@InterceptorBinding
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Traced {
@Nonbinding
boolean traceFull() default true;
}
然后,我定义了一个拦截器实现
@Interceptor
@Traced
public class TracingInterceptor implements Serializable { ... }
在实现中,我希望检查traceFull-参数设置了哪个值。(我不想为true、false和null实现三个拦截器)
所以我的实现检查被拦截方法的Interceptor-Binding-Annotation:
Traced traceAnnotation = context.getMethod().getAnnotation(Traced.class);
if (traceAnnotation != null && traceAnnotation.traceFull()) { ... }
这可以很好地工作,但是如果我使用一个构造型或者一个嵌套的拦截器绑定,那么我不会得到这个方法的@Traced注解,我也不能检查设置的值。
所以我的问题是:如何在我的拦截器实现中获得“调用”绑定?
发布于 2012-01-26 03:58:42
这在CDI 1.0中是不可能的,但在CDI 1.1中应该是可能的
发布于 2014-07-03 19:09:16
您甚至可以使用反射来解析构造型中的注释。
在同样的情况下(在拦截器中需要额外的非绑定信息),我实现了一个实用方法:
public <T extends Annotation> T findBindingAnnotation( Class<T> bindingType, InvocationContext ic )
{
Method method = ic.getMethod();
if ( method != null && method.isAnnotationPresent( bindingType ) )
{
return method.getAnnotation( bindingType );
}
Class<? extends Object> type = ic.getTarget().getClass();
if ( type.isAnnotationPresent( bindingType ) )
{
return type.getAnnotation( bindingType );
}
T annotationFromStereoType = annotationFromStereoType( bindingType, type );
if ( annotationFromStereoType != null )
{
return annotationFromStereoType;
}
throw new UnsupportedOperationException( "no binding annotation found: " + bindingType.getCanonicalName() );
}
private <T extends Annotation> T annotationFromStereoType( Class<T> bindingType, Class<? extends Object> type )
{
for ( Annotation annotation : type.getAnnotations() )
{
Class<? extends Annotation> annotationType = annotation.annotationType();
if ( annotationType.isAnnotationPresent( Stereotype.class ) )
{
if ( annotationType.isAnnotationPresent( bindingType ) )
{
return annotationType.getAnnotation( bindingType );
}
else
{
T recursiveLookup = annotationFromStereoType( bindingType, annotationType );
if ( null != recursiveLookup )
{
return recursiveLookup;
}
}
}
}
return null;
}
https://stackoverflow.com/questions/8990998
复制相似问题