JEE6:在拦截器实现中获取绑定注释

时间:2012-01-24 17:09:31

标签: java-ee cdi interceptor

我有一个拦截器绑定,参数化:

@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-parameter。 (我不想为true,false和null实现三个拦截器实现)

所以我的实现检查拦截方法的Interceptor-Binding-Annotation:

Traced traceAnnotation = context.getMethod().getAnnotation(Traced.class);
if (traceAnnotation != null && traceAnnotation.traceFull()) { ... }

这样可以正常工作但如果我使用Stereotype或嵌套拦截器绑定,那么我不会得到方法的@Traced annotatopn,我无法检查设置的值。

所以我的问题是:如何在拦截器实现中获得'调用'绑定?

2 个答案:

答案 0 :(得分:1)

您甚至可以使用反射来解析构造型中的注释。

处于相同的情况(在拦截器中需要额外的非绑定信息),我实现了一个实用方法:

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;
}

答案 1 :(得分:0)

这在CDI 1.0中是不可能的,但应该在CDI 1.1中