aop概念说明
https://blog.csdn.net/qq_41256238/article/details/107123322
配置AOP
配置过程概述
- 需要有待增强方法,也就是切入点。
- 需要有增强方法,也就是通知。
- 在配置文件中配置aop。
配置实例
-
pom.xml 需要导入的依赖
<dependencies> <!--spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!--aop--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> </dependencies>
-
普通java类,这个类中的方法需要被增强
public class Demo { public void print1() { System.out.println("running1...."); } public void print2() { System.out.println("running2...."); } public void print3() { System.out.println("running3...."); } }
-
切面类,也就是通知方法所在的类
/** * 切面类 */ public class Aop { /** * 打印当前系统时间 */ public void printTime() { System.out.println(System.currentTimeMillis()); } }
-
applicationContext.xml 配置文件,配置aop
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--待增强方法所在类的bean--> <bean id="demo" class="com.ithiema.demo.Demo"/> <!--切面类bean--> <bean id="aop" class="com.ithiema.aop.Aop"/> <!--配置aop--> <aop:config> <!-- 配置切入点 expression:指定切入点的规则,也就是要拦截哪些待增强方法(所谓的切入点) --> <aop:pointcut id="pt" expression="execution(* com.ithiema..*.*(..))"/> <!--配置切面,用于整合切入点和通知 注意:要引用切面类的bean--> <aop:aspect ref="aop"> <!-- before:前置通知,在拦截方法之前指定的通知 pointcut-ref:引用切入点,符合这个规则的方法都会被拦截 method:指定对切入点进行增强的方法。 --> <aop:before method="printTime" pointcut-ref="pt"/> </aop:aspect> </aop:config> </beans>
切入点表达式
切入点表达式定义
<aop:pointcut id="pc" expression="execution (* com.itheima.service..*.*(..))"/>
其中expression="execution (* com.itheima.service..*.*(..))"/>
的配置规则如下
execution(modifiers-pattern? ret-ty