Aspectj

配置

  1. 启用IDEA版本的aspectj插件

  2. Project Setting –> Compiler –> Java Compiler设置编译器为Ajc

  3. Path to Ajc compiler 设定 aspjectjtools.jar 的路径,下载地址:https://mvnrepository.com/artifact/org.aspectj/aspectjtools

  4. 项目需要引用 aspectjrt.jar,maven库地址:https://mvnrepository.com/artifact/org.aspectj/aspectjrt

maven 引入

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjtools</artifactId>
    <version>1.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.1</version>
</dependency>

代码

  • HelloWorld.java
public class HelloWorld {

    public void test(){
        System.out.println("hello aspectj");
    }

}
  • App.java
public class App {

    public static void main(String[] args) {
        HelloWorld h = new HelloWorld();
        h.test();
    }

}
  • MethodAspect.java
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MethodAspect {

    @Pointcut("execution(* test())")
    public void excute(){

    }
    @Before("excute()")
    public void beforedo(){
        System.out.println("before");
    }

}

运行日志

before
hello aspectj

运行嵌入

demo的代码不变,但是 VM 需要增加

-javaagent:~/aspectjweaver.jar

以及指定目录下的配置文件 META-INF/aop.xml

如果需要在不修改原有业务基础上针对已有项目可以使用运行嵌入,相对而言,编译嵌入在部署上更方便。

参考资料

https://www.eclipse.org/aspectj/doc/released/progguide/index.html

https://www.jetbrains.com/help/idea/aspectj.html

https://blog.csdn.net/xqj198404/article/details/77651768