首先,还是一样的,需要导入AOP的依赖。还有AOP的约束。
<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
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解驱动-->
<context:annotation-config/>
<!--指定要扫描的包-->
<context:component-scan base-package="com.huchuan"/>
<!--开启aop注解支持-->
<aop:aspectj-autoproxy/>
</beans>
第二,还是和之前的一样,创建一个普通类,在里边写增强方法。
第三,需要给这个类声明成一个切面类。使用@Aspect注解。还需要将这个类交给Spring管理,使用@Component注解。
第四步,在这个自定义类的方法上添加注解,表明它切入那些方法,是什么类型的通知,前置,后置,还是环绕。
第五步,在配置文件中开启AOP的注解支持为自动代理。需要注意的是,Spring默认使用的是JDK的动态代理,如果在开启AOP的注解的时候,把proxy-target-class="true"的话,Spring就会使用CGLIB来实现。
自定义切面类
package com.huchuan.DiyAspect;
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;
import org.springframework.stereotype.Component;
/**
* @Author 胡川
* @Date 2021年07月09日 10:34
*/
@Component
@Aspect
public class DiyBefore {
@Before("execution(* com.huchuan.mapper.UserMapperImpl.*(..))")
public void beforeLog(){
System.out.println("===============方法执行前==============");
}
@After("execution(* com.huchuan.mapper.UserMapperImpl.*(..))")
public void afterLog(){
System.out.println("===============方法执行后==============");
}
@Around("execution(* com.huchuan.mapper.UserMapperImpl.*(..))")
public void around(ProceedingJoinPoint pj){
System.out.println("环绕前!");
try {
// 执行方法 可以通过pj这个对象拿到这个方法的信息,类似于动态代理里的参数列表值那些东西都可以取
Object proceed = pj.proceed();
System.out.println(proceed);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("环绕后!");
}
}
Spring配置文件
<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
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解驱动-->
<context:annotation-config/>
<!--指定要扫描的包-->
<context:component-scan base-package="com.huchuan"/>
<!--开启aop注解支持-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>