🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. AspectJ框架** AspectJ 是一个独立的 AOP 框架,Spring 整合了该框架来实现注解式的 AOP 编程。 ``` ====常用的 AOP 注解==== @Order(int value) 决定切面对象其作用的顺序,value越小越先被执行 @Aspect 将切面对象注入IoC容器中 @Pointcut 定义切入点 @Before 前置增强 @After 最终增强 @AfterReturning 后置增强 @AfterThrowing 异常增强 @Around 环绕增强 ``` <br/> **2. AOP注解使用步骤** (1)在`resources/ApplicationContext.xml`中开启AspectJ代理和包扫描。 ```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" xmlns:context="http://www.springframework.org/schema/context" 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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--开启包扫描--> <context:component-scan base-package="com.learn.spring06.*" /> <!-- 开启AspectJ代理 --> <aop:aspectj-autoproxy /> </beans> ``` (2)目标对象。 ```java @Service public class StudentServiceImpl implements StudentService { @Override public void add(int x, int y) { System.out.println("------目标函数的输出------\n" + (x + y)); } } ``` (3) 创建切面对象。 ```java @Component @Aspect @Order(1) // 该注解可选 public class AspectLogger { private static final Logger logger = Logger.getLogger(AspectLogger.class); @Before("execution(* com.learn.spring.annotation.service..*.*(..))") public void printLogger(JoinPoint jPoint) { logger.info("\n------增强函数的输出------" + "\n增强方式:前置增强" + "\n目标对象:" + jPoint.getTarget() + "\n目标函数:" + jPoint.getSignature().getName() + "\n目标函数的参数:" + Arrays.toString(jPoint.getArgs())); } } ``` 切入点还可以如下编写: ```java // 写法1 @Before("execution(* com.learn.spring.annotation.service.impl.StudentServiceImpl.add(..))") public void printLogger(JoinPoint jPoint) {...} // 写法2:先封装切入点,再应用到增强函数中 @Pointcut(value = "execution(* com.learn.spring.annotation.service.impl.StudentServiceImpl.add(..))") public void addStudentPointcut() {/* 封装的切入点*/} @Before("addStudentPointcut()") public void printLogger(JoinPoint jPoint) {...} // 写法3:可以同时配置多个切入点,使用&&或||来隔开 @Pointcut("(execution(public void add(int, int))) && (execution(public void delete())) ") public void addStudentPointcut() { /*封装的切入点 */} @Before("addStudentPointcut()") public void printLogger(JoinPoint jPoint) {...} ``` (4)测试结果。 ``` ------增强函数的输出------ 增强方式:前置增强 目标对象:com.learn.spring06.service.impl.StudentServiceImpl@1eb5174b 目标函数:add 目标函数的参数:[10, 20] ------目标函数的输出------ 30 ```