Java Spring 学习笔记 022(注解实现AOP)
来自B站【狂神说Java】Spring5最新完整教程IDEA版通俗易懂
方式三:使用注解实现
1. 代码
package com.kuang.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* 方式三:使用注解方式实现AOP
* "@Aspect" 标注这个类是一个切面
*/
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void before() {
System.out.println("AnnotationPointCut.before");
}
@After("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void after() {
System.out.println("AnnotationPointCut.after");
}
// 在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点;
@Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("AnnotationPointCut.around 环绕前");
// 获得签名
System.out.println("signature: " + joinPoint.getSignature());
// 执行方法
Object proceed = joinPoint.proceed();
System.out.println("AnnotationPointCut.around 环绕后");
System.out.println("proceed: " + proceed);
}
}
2. 配置
<?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
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="userService" class="com.kuang.service.UserServiceImpl"/>
<!-- <bean id="log" class="com.kuang.log.Log"/>
<bean id="afterLog" class="com.kuang.log.AfterLog"/>-->
<!-- 方式一:使用原生Spring的API接口 -->
<!-- 配置AOP:需要导入aop的约束 -->
<!-- <aop:config>
<!– 切入点:expression:表达式,execution(要执行的位置! * * * * *) –>
<aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<!– 执行环绕增加 –>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>-->
<!-- 方式二:自定义类 -->
<!-- <bean id="diyPointCut" class="com.kuang.diy.DiyPointCut"/>
<aop:config>
<!– 自定义切面,ref要引用的类 –>
<aop:aspect ref="diyPointCut">
<!– 切入点 表达式 (修饰符返回值 哪个类)–>
<aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<!– 通知 –>
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>-->
<!-- 方式三 -->
<bean id="annotationPointCut" class="com.kuang.diy.AnnotationPointCut"/>
<!--
开启注解支持
proxy-target-class="false" 默认是false,表示使用 JDK 实现动态代理(用的是接口),一般使用默认的即可
proxy-target-class="true" 设置为true,表示使用 cglib 实现动态代理(用的是类)
-->
<aop:aspectj-autoproxy/>
</beans>
浙公网安备 33010602011771号