1

Suppose I have an annotation as following:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBOperation
{
    boolean isReadOperation() default true;
}

Then in the Aspect, how could I want to write two pointcuts, one for all the method annotated with @DBOperation(isReadOperation=true) and one for @DBOperation(isReadOperation=false)?

kriegaex
  • 63,017
  • 15
  • 111
  • 202
vincent zhang
  • 444
  • 5
  • 20

1 Answers1

0

The syntax is actually pretty straightforward. Here is an MCVE:

Marker annotation:

package de.scrum_master.app;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(METHOD)
public @interface DBOperation {
  boolean isReadOperation() default true;
}

Driver application:

package de.scrum_master.app;

public class Application {
  public static void main(String[] args) {
    Application application = new Application();
    application.doSomething();
    application.readValue("name");
    application.writeValue("name", "John Doe");
  }

  public void doSomething() {}

  @DBOperation
  public int readValue(String fieldName) {
    return 11;
  }

  @DBOperation(isReadOperation = false)
  public String writeValue(String fieldName, Object value) {
    return "dummy";
  }
}

Aspect:

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class DBOperationAspect {
  @Before("execution(@de.scrum_master.app.DBOperation(isReadOperation=true) * *(..))")
  public void interceptRead(JoinPoint joinPoint) throws Throwable {
    System.out.println("Read operation: " + joinPoint);
  }

  @Before("execution(@de.scrum_master.app.DBOperation(isReadOperation=false) * *(..))")
  public void interceptWrite(JoinPoint joinPoint) throws Throwable {
    System.out.println("Write operation: " + joinPoint);
  }
}

Console log:

Read operation: execution(int de.scrum_master.app.Application.readValue(String))
Write operation: execution(String de.scrum_master.app.Application.writeValue(String, Object))
kriegaex
  • 63,017
  • 15
  • 111
  • 202