将setter调用到使用AspectJ注释的字段

时间:2017-04-12 16:30:00

标签: java aspectj setter

我希望拦截在这种情况下使用MyAnnotation注释的字段的所有赋值。如果在使用reflction分配值时它工作得更好。 这是我尝试过的,但它没有运行,我认为其他可能是错误的:

public privileged aspect MyAnnotationAspect {

    pointcut hasAnnotation(MyAnnotation annotation) : @annotation(annotation);

    pointcut methodExecution() : execution(* *(..));

    Object around(MyAnnotation annotation) : set(String word) && methodExecution() && hasAnnotation(annotation) {
        Object result = null;
        try {
            result = proceed(annotation, "new"); //Just to try I want to assign "new" instead of the variable word
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        }
        return result;
    }

}

它表示该方法的参数太多了。谁能帮我?谢谢!

修改

现在抛出“警告:(10,0)ajc:在aspects.AnnotationAspect中定义的建议尚未应用[Xlint:adviceDidNotMatch]”

这是我的方面:

public aspect AnnotationAspect {

    pointcut hasAnnotation(Annotation annotation) : @annotation(annotation);

    Object around(Annotation annotation, String word) : hasAnnotation(annotation) && set(String *) && args(word) {
        Object result = null;
        System.out.println(thisJoinPoint);
        try {
            result = proceed(annotation, "intercepted");
        } catch (RuntimeException ex) {
            throw ex;
        }
        return result;
    }
}

这是注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Annotation {
}

我有一个假人来测试它:

class DummyEntity{

  @Annotation
  var name: String =_

  def setName(n: String): Unit ={
    name = n
  }
}

这是我正在测试它的测试:

public class AnnotationAspectTest {

    private DummyEntity dummyEntity;

    @Before
    public void setUp(){
        dummyEntity = new DummyEntity();
    }

    @Test
    public void testing(){
        dummyEntity.setName("newName");
        Assert.assertEquals("intercepted", dummyEntity.name());
    }
}

1 个答案:

答案 0 :(得分:1)

methodExecution()在这里适得其反,因为您不想捕获方法执行,而是捕获字段写入权限。因为set(..) && execution(..)是互斥的,所以这没有逻辑意义。

此外,您需要通过args()将指定的值绑定到参数,以便能够对其进行修改。

package de.scrum_master.aspect;

import de.scrum_master.app.MyAnnotation;

public aspect MyAnnotationAspect {
  Object around(MyAnnotation annotation, String word) :
    @annotation(annotation) && set(String *) && args(word)
  {
    System.out.println(thisJoinPoint);
    Object result = null;
    try {
      result = proceed(annotation, "altered value");
    } catch (Throwable ex) {
      throw new RuntimeException(ex);
    }
    return result;
  }
}
相关问题