我對AOP相當陌生。我試圖在沒有Spring的Maven項目中使用AspectJ創建註釋。但是,我正在嘗試使用@Aspect調用的方法未被調用。在沒有彈簧的情況下使用AspectJ註釋
這是我的聚甲醛是什麼樣子:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>tanvi</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjrt -->
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver -->
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.5.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.8</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
</configuration>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
的註釋是這樣的:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface HasAccess {
Access[] accesses();
String message() default "You are not allowed to perform this operation";
}
我創造了我的註解註釋處理器:
@Aspect
public class HasAccessAdvice {
// @Before("execution(* *.*(..)) && @annotation(testAnnotation) ")
@Before("execution(* *.*(..)) && @annotation(hasAccess)")
public void myBeforeLogger(JoinPoint joinPoint, HasAccess hasAccess) {
System.out.println("Okay - we're in the before handler...");
System.out.println("The test annotation value is: " + hasAccess.accesses().toString());
Signature signature = joinPoint.getSignature();
String methodName = signature.getName();
String stuff = signature.toString();
String arguments = Arrays.toString(joinPoint.getArgs());
System.out.println("Write something in the log... We are just about to call method: "
+ methodName + " with arguments " + arguments + "\nand the full toString: "
+ stuff);
}
}
我稱其爲這一呼籲:
public class TestMe {
@HasAccess(accesses = {Access.CREATE_PURCHASE})
public void createPurchase(BigDecimal bigDecimal) {
System.out.println("create Purchase called");
}
}
我創建了一個文件aop.xml文件並將它放到同一文件夾中的pom.xml。
<aspectj>
<aspects>
<aspect name="HasAccessAdvice"/>
</aspects>
</aspectj>
當我調用createPurchase方法時,它不運行首先調用的@Before方法。請幫我解決我缺少的問題。我發現的大多數文檔/答案都是與Spring對齊的。任何指向任何教程的指針,甚至是在沒有Spring的情況下創建簡單註釋的另一種方式,都將不勝感激。
你是如何運行你的代碼? – mateuszlo