spring之aop基于注解开发配置
程序员文章站
2022-07-12 23:15:02
...
导入xml约束及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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启自动扫描组件-->
<context:component-scan base-package="com.itcast"></context:component-scan>
<!--开启spring支持aop注解开发-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
Logger.java注解配置切面,选择环绕通知进行方法增强,自动增强注解开发执行顺序有问题
/**
* @Date 2019/9/9 17:46
* by mocar
*/
@Component
//@EnableAspectJAutoProxy//开启spring对aop注解开发的支持,等同于xml里的配置
@Aspect//表示当前类为切面类
public class Logger {
@Pointcut("execution(* com.itcast.service.impl.*.*(..))")
private void pt1(){}
//@Before("pt1()")
public void beforeAD(){
System.out.println("前置通知开始执行.............");
}
//@AfterReturning("pt1()")
public void afterRunAD(){
System.out.println("后置通知开始执行.............");
}
//@AfterThrowing("pt1()")
public void throwAD(){
System.out.println("异常通知开始执行.............");
}
//@After("pt1()")
public void afterAD(){
System.out.println("最终通知开始执行.............");
}
/*环绕通知
* 就相当于动态代理的整个过程
* 相当于手动编码控制增强,无需在xml里配置
* */
@Around("pt1()")
public Object aroundAD(ProceedingJoinPoint pjp){
Object rsValue=null;
try {
Object[] pjpArgs = pjp.getArgs();//获取参数
//前置通知
System.out.println("环绕通知开始执行...前置通知..........");
//Object proceed(Object[] var1) throws Throwable;
rsValue = pjp.proceed(pjpArgs);//等价于动态代理中的 methed.invoke(obj,args)
//后置通知
System.out.println("环绕通知开始执行...后置通知..........");
} catch (Throwable e) {
//异常通知
System.out.println("环绕通知开始执行...异常通知..........");
throw new RuntimeException(e);
}finally {
//最终通知
System.out.println("环绕通知开始执行...最终通知..........");
}
return rsValue;
}
}
自动增强注解开发执行顺序有问题截图
上一篇: spring aop注解开发
下一篇: 枚举类型(enum)