AspectJ切入点和建议 [英] AspectJ pointcuts and advice

查看:147
本文介绍了AspectJ切入点和建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要添加不属于特定类别的项目,我必须执行一项警告政策,除了允许的三个项目之外,不允许添加此类项目....

I have to enforce a policy issuing a warning if items not belonging to a particular category are being added, apart from the three which are allowed and disallowing such additions.....

到目前为止,我能够找到这些项目并发出警告....但是不确定如何阻止它们被添加....

So far i am able to find the items and issue warning.... but not sure how to stop them from being added....

例如

允许的类别鞋子和袜子

但是,如果我尝试将蔬菜项目添加到库存中,则应该给我一个警告,提示不允许分类../nItem将不会添加到库存中" ...然后继续进行下一个项目. ...

but if i try and add a vegetable item to the inventory it should give me a warning saying "category not allowed../nItem will not be added to inventory"..... and then proceed to the next item....

这是我到目前为止写的.....

This is what i've written so far.....

pointcut deliverMessage() :
    call(* SC.addItem(..));

pointcut interestingCalls(String category) :
    call(Item.new(..)) && args(*, *, category);

before(String category): interestingCalls(category) { 
    if(category.equals("Socks")) {       
        System.out.println("category detect: " + category);
    else if(category.equals("Shoes"))
        System.out.println("category detect: " + category);
    else {
        check=true; 
        System.out.println("please check category " + category);
    }
}

推荐答案

为什么不使用around方面.然后,如果它们的类别不正确,那么您就不会进入该方法,因此,如果被跳过的方法只是在进行添加,则会被跳过.

Why not use the around aspect instead. Then, if they are not of the correct category you don't go into that method, so it gets skipped, if the skipped method is just doing the adding.

更新:

这是曼宁出版社(Manning Publication)的《 AspectJ In Action》中的一个示例.

Here is an example from AspectJ In Action, by Manning Publication.

public aspect ProfilingAspect {
  pointcut publicOperation() : execution(public * *.*(..));
  Object around() : publicOperation() {
    long start = System.nanoTime();
    Object ret = proceed();
    long end = System.nanoTime();
    System.out.println(thisJoinPointStaticPart.getSignature()
      + " took " + (end-start) + " nanoseconds");
    return ret;
  }
}

因此,如果您想检查是否应添加项目,如果它是允许的类别,则只需调用proceed,否则您可能只是返回一个空值.

So, if you wanted to check if you should add the item, if it is an allowed category then just call proceed, otherwise you would just return a null perhaps.

这篇关于AspectJ切入点和建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆