编译切入
参考文档地址:
https://www.jetbrains.com/help/idea/aspectj.html
步骤
- 启用IDEA版本的aspectj插件
- Project Setting –> Compiler –> Java Compiler设置编译器为Ajc
- Path to Ajc compiler设定aspjectjtools.jar的路径,下载地址:https://mvnrepository.com/artifact/org.aspectj/aspectjtools
- 项目需要引用aspectjrt.jar,maven库地址:https://mvnrepository.com/artifact/org.aspectj/aspectjrt
demo代码
入口类
package test.s;
public class App {
public static void main(String args[]) {
System.out.println("start");
hello h = new hello();
h.test();
System.out.println("end");
}
}
业务类
package test.s;
public class hello {
public void test(){
System.out.println("hello aspectj");
}
}
切面类
package test.s;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class Monitor {
@Pointcut("execution(* test())")
public void excute(){
}
@Before("excute()")
public void beforedo(){
System.out.println("before");
}
}
这是基于编译时嵌入aop代码
运行嵌入
demo的代码不变,但是VM需要增加-javaagent:pathto/aspectjweaver.jar以及指定目录下的配置文件META-INF/aop.xml
如果需要在不修改原有业务基础上针对已有项目可以使用运行嵌入,相对而言,编译嵌入在部署上更方便。