一、快速入门
1. 导入 AOP 相关坐标
2. 创建目标接口和目标类(内部有切点)
3. 创建切面类(内部有增强方法)
4. 将目标类和切面类的对象创建权交给spring
5. 在applicationContext.xml中配置织入关系
6. 测试代码
代码实现:
新建一个module:itheima_spring_aop
1. 导入 AOP 相关坐标
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.itheima</groupId> <artifactId>itheima_spring_aop</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- 导入spring的context坐标,context依赖aop --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.22.RELEASE</version> </dependency> <!-- aspectj的织入 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.19</version> </dependency> </dependencies> </project>
2. 创建目标接口和目标类(内部有切点)
package com.itheima.aop; public interface TargetInterface { public void save(); }
package com.itheima.aop; public class Target implements TargetInterface { public void save() { System.out.println("save running ..."); } }
3. 创建切面类(内部有增强方法)
package com.itheima.aop; public class MyAspect { public void before(){ System.out.println("前置增强......"); } }
4. 将目标类和切面类的对象创建权交给spring
resources->applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--配置目标类,目标对象--> <bean id="target" class="com.itheima.aop.Target"></bean> <!--配置切面类,切面对象--> <bean id="myAspect" class="com.itheima.aop.MyAspect"></bean> </beans>
5. 在applicationContext.xml中配置织入关系
导入aop命名空间
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
配置切点表达式和前置增强的织入关系关系
<!--配置织入:告诉spring框架 哪些方法(切点)需要进行哪些增强(前置、后置...) --> <aop:config> <!--引用myAspect的Bean为切面对象,即声明切面--> <aop:aspect ref="myAspect"> <!--配置Target的save方法执行时要进行myAspect的before方法前置增强,即切面:切点+通知--> <aop:before method="before" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:before> </aop:aspect> </aop:config>
标签:XML,10,xml,spring,Spring17,aop,AOP,public,itheima From: https://www.cnblogs.com/ajing2018/p/17375114.html