面向切面编程的目的就是:在不改变别人的代码的前提下,在别人代码方法执行前或后,执行(切入自己的逻辑)
准备:idea+maven+aspectjweaver-1.8.9.jar
结构图:
pom.xml内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
< dependencies > < dependency > < groupId >org.aspectj</ groupId > < artifactId >aspectjrt</ artifactId > < version >1.8.9</ version > </ dependency > < dependency > < groupId >org.aspectj</ groupId > < artifactId >aspectjtools</ artifactId > < version >1.8.9</ version > </ dependency > < dependency > < groupId >org.aspectj</ groupId > < artifactId >aspectjweaver</ artifactId > < version >1.8.9</ version > </ dependency > </ dependencies > < build > < plugins > < plugin > < groupId >org.codehaus.mojo</ groupId > < artifactId >aspectj-maven-plugin</ artifactId > < executions > < execution > < goals > < goal >compile</ goal > </ goals > </ execution > </ executions > < configuration > < complianceLevel >1.8</ complianceLevel > < source >1.8</ source > < target >1.8</ target > < aspectDirectory >src/main/java</ aspectDirectory > </ configuration > </ plugin > </ plugins > </ build > |
切面类
1
2
3
4
5
6
7
|
public aspect Staspect { public pointcut kkMethod(): execution( public String aop.Test.kk()); before(): kkMethod() { System.out.println( "先执行我" ); } } |
主类
1
2
3
4
5
6
7
8
9
10
|
public class Test { public String kk(){ return "23" ; } public static void main(String[] args) { Test test= new Test(); System.out.println(test.kk()); } } |
新建一个aop.xml(在META-INFO文件夹下)
1
2
3
4
5
6
7
|
<? xml version = "1.0" encoding = "UTF-8" ?> < aspectj > < aspects > < aspect name = "aop.Staspect" /> </ aspects > < weaver options = "-XaddSerialVersionUID" ></ weaver > </ aspectj > |
打jar包,执行命令:mvn clean package
注意我的结构图,classes下面如果有两个类就是编译成功了
挑出jar包,执行命令:
java -javaagent:/home/admin/aspectjweaver-1.8.9.jar -classpath aspecttest-1.0-SNAPSHOT.jar aop.Test
注意:-javaagent后面的参数是你电脑aspectjweaver-1.8.9.jar的路径
到此这篇关于Java aop面向切面编程(aspectJweaver)案例详解的文章就介绍到这了,更多相关Java aop之aspectJweaver内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_35555139/article/details/78529191