【问题标题】:CDI interceptor for a specific type特定类型的 CDI 拦截器
【发布时间】:2012-07-24 09:46:13
【问题描述】:
@InterceptorBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresPageReload {
}

public interface Page{
    public static final String LOAD_STR = "load";
    public void load();
}
@RequestScoped
public class PageImpl1 implements Page{
    public void load(){
        //...
    }

    @RequiresPageReload
    public String foo(){
        //...
        return "foo1";
    }
}
@RequestScoped
public class MyObject{
    @RequiresPageReload
    public String foo2(){
        //...
        return "foo2";
    }
}

@RequiresPageReload
@Interceptor
public class RequiresPageReloadInterceptor implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @AroundInvoke
    public Object forceReload(InvocationContext context) throws Exception {
        Object result = context.proceed();
        context.getMethod().getDeclaringClass().getDeclaredMethod(Page.LOAD_STR).invoke(context.getTarget()); //***
        return result;
    }

}

在标有星号的那一行,我当然可以通过反射检查该方法是否存在,并据此决定要做什么。 但我想知道是否有更好的方法来实现相同的行为? 例如,是否可以将拦截器仅关联到特定类型(在此示例中,假设我不希望 MyObject 的 foo2() 方法被拦截,因为此类对象未实现 Page)?我也考虑过使用装饰器,但问题是“foo”的方法不属于接口..

谢谢!

【问题讨论】:

    标签: jakarta-ee cdi interceptor


    【解决方案1】:

    听起来你想要的是decorator

    【讨论】:

    • 嗨!感谢您的回答..正如我写的“我也考虑过使用装饰器,但问题是“foo”的方法不属于接口..”..我确实注释了不属于接口的方法,所以装饰者无济于事.. :(
    • CDI 中没有任何东西可以真正做到这一点。不过,您可能可以将其作为扩展来实现。
    猜你喜欢
    • 2020-06-17
    • 2014-03-10
    • 2017-01-28
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多