article/java/spring aop 二.md
2022-08-28 14:37:13 +08:00

116 lines
2.8 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 切入点表达式
作用 用来匹配切入的方法。
execution(切入点表达式 方法返回值 )
execution([方法修饰符] 方法返回类型 全类名.方法名(参数类型))
**通配符 ***
- 匹配方法返回值
- 匹配方法的包名
- 匹配方法的类名
- 匹配方法的方法名
- 匹配方法的参数类型
**通配符** `..` 标识任意多个
- 匹配任意层级的包
- 匹配任意个数 任意类型的参数
例子:
- 标识 cn.x47包下的任意子包的所有方法任意参数
```xml
<aop:beforemethod="printOne"pointcut="execution(public * cn.x47..*(..))"/>
```
+ 匹配任意层级的TargetObject对象
~~~xml
<aop:beforemethod="printOne"pointcut="execution(public void ..TargetObject.print2())"/>
~~~
+ 匹配任意个数 任意类型的参数
~~~xml
<aop:beforemethod="printOne"pointcut="execution(public void org.example.TargetObject.print2(..))"/>
~~~
+ 匹配以Object结尾的对象 2结尾 任意参数类型 的方法
~~~xml
<aop:beforemethod="printOne"pointcut="execution(public void org.example.*Object.*2(..))"/>
~~~
**切入点配置方式**
+ 局部切入点
+ 切面间共享切入点
+ 将切入点表达式写在切面配置外面
+ 例子:
~~~xml
<aop:config>
<aop:pointcut id="abc" expression="execution(
public void org.example.TargetObject.print2())"/>
<aop:aspect ref="advice">
<aop:before method="printOne" pointcut-ref="abc"/>
</aop:aspect>
</aop:config>
~~~
+ 切面内共享切入点
+ 将切入点配置在切面里 切入点外
+ 例子:
~~~xml
<aop:config>
<aop:aspect ref="advice">
<aop:pointcut id="abc" expression="execution(
public void org.example.TargetObject.print2())"/>
<aop:before method="printOne" pointcut-ref="abc"/>
</aop:aspect>
</aop:config>
~~~
**切面执行顺序**
+ 同一切面
+ 先配置先执行
+ 不同切面
+ 前置 前配置先执行
+ 后置 先配置后执行 后配置先执行
**通知获取切入点参数**
+ 通过 JoinPoint 对象获取
~~~xml
public void printOne(JoinPoint jp) {
Object[] args = jp.getArgs();
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
}
}
~~~
+ 通过切入点指定参数类型 参数形参
```xml
//切入点配置
<aop:before method="printOne" pointcut="execution(* org.example.TargetObject.print2(String)) && args(a)"/>
```
```java
//通知
public void printOne(String a) {
System.out.println("我是参数" + a);
System.out.println("我是通知");
}
```
**注解配置**
执行优先级
环绕在前 前置后置 在后 返回最后