spring-aop入门案例
采用输出日志作为示例。 访问service方法自动记录日志
1.创建项目,导入spring-aop,aspectjweare依赖
<dependencies> <!-- spring-ioc: 以后使用spring其他功能,都必须先导入ioc相关依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- spring-aop spring自身aop编程包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- spring依赖的第三方工具包(提供切入点表达式语法) --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> </dependencies>
2.创建service接口和实现
package com.lemon.service; public interface LemonService { void save(); void delete(); void update(); }
package com.lemon.service.impl; import com.lemon.service.LemonService; public class LemonServiceImpl implements LemonService { @Override public void save() { System.out.println("新增"); } @Override public void delete() { System.out.println("删除"); } @Override public void update() { System.out.println("修改"); } }
3.创建切面类
package com.lemon.log; /** * 日志切面类 */ public class LogAspect { /** * 通知方法(插入到目标方法的前面) */ public void writeLog(){ System.out.println("before======="); } }
4.配置切面类
<?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: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"> <!-- 1.创建目标对象 --> <bean id="lemonService" class="com.lemon.service.impl.LemonServiceImpl"/> <!-- 2.创建切面对象 --> <bean id="logAspect" class="com.lemon.log.LogAspect"/> <!-- 3.切面配置 --> <aop:config> <!-- 切面配置 = 通知(advice)+切入点(pointcut)--> <!-- ref: 引用切面类对象 --> <aop:aspect ref="logAspect"> <!-- 定义切入点 --> <!-- id: 定义切入点的别名 expression: 切入点表达式(用于定义需要切入的方法) --> <aop:pointcut id="pt" expression="execution(* com.lemon.service.impl.LemonServiceImpl.*(..))"/> <!-- 定义通知 --> <!-- method: 使用切面类的哪个方法作为通知方法 pointcut-ref: 关联切入点 --> <!-- 前置通知 --> <aop:before method="writeLog" pointcut-ref="pt"/> </aop:aspect> </aop:config> </beans>
5. 测试
package com.lemon; import com.lemon.service.LemonService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; //测试AOP public class App { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-aop.xml"); LemonService lemonService = (LemonService) ac.getBean("lemonService"); System.out.println("代理对象"+lemonService.getClass()); lemonService.save(); lemonService.delete(); lemonService.update(); } }