【问题标题】:JEE6 Interceptors - extract method variableJEE6 拦截器 - 提取方法变量
【发布时间】:2013-09-21 22:13:46
【问题描述】:

是否可以在方法变量被拦截时提取一次/同时提取它的值?我不想截取参数而是方法中的属性值?例如

Business Logic: 

@MyInterceptor
void myMethod(Object o){

 ArrayList myList= null;
 myList= dao.getRecords(o.getId) //intercept the result of this dao call


//I only want to call doWork after I have 'validated' contents of myList in interceptor

 doWork(myList)


}


The Interceptor:  

@Interceptor
@MyInterceptor
MyInterceptor{

@AroundInvoke{
public Object invoke(InvocationContext ctx) throws Exception {

 //retrieve the contents of myList above and perform validation
 //if it passes validation call ctx.proceed else return error

}

}

谢谢

【问题讨论】:

    标签: java java-ee-6 cdi interceptor jboss-weld


    【解决方案1】:

    恐怕你不能用拦截器真正做到这一点,因为它们无法访问方法内部变量(只需查看 InvocationContext javadocs)。因此,您唯一的机会就是将 myList 设为 beans 属性,然后在您的拦截器中执行此操作。

    @AroundInvoke{
    public Object invoke(InvocationContext ctx) throws Exception {
        if(ctx.getTarget() instanceof BeanWithListProperty) {
            Object toProceed = ctx.proceed(); 
            BeanWithListProperty bean = (BeanWithListProperty) ctx.getTarget();
            List list = bean.getMyList();
            return toProceed;
        }
        return ctx.proceed();
    }
    

    其他选项是使用Decorators,这将导致代码更具可读性和效率。

    但是我不太喜欢这些解决方案,在我看来,您的代码确实设计得不好,您想达到什么目的?

    【讨论】:

    • 谢谢,我考虑的另一个选择是将 DAO 移至拦截器,但它有其他缺点,并不适合所有用例。谢谢您的回复
    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    相关资源
    最近更新 更多