JAVA全系列 教程
3762个小节阅读:7094.7k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
Aspectj方式实现AOP的通知类不需要实现任何的接口,直接声明一个普通java类即可,然后在类中直接定义通知方法即可,方法名随意,但是建议方法名见名知意。
xxxxxxxxxx
package com.bjsxt.advice;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyAdvice {
//前置通知方法
public void before(){
System.out.println("我是前置通知方法...");
}
//后置通知方法
public void after(){
System.out.println("我是后置通知方法...");
}
//环绕通知方法
public Object round(ProceedingJoinPoint pp) throws Throwable {
System.out.println("环绕---前");
//放行
Object proceed = pp.proceed();
System.out.println("环绕---后");
return proceed;
}
//异常通知方法
public void myThrow(Exception ex){
System.out.println("我是异常通知......"+ex.getMessage());
}
}
xxxxxxxxxx
<?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
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置真实对象的bean-->
<bean id="us" class="com.bjsxt.service.impl.UserServiceImpl"></bean>
<!--配置通知bean-->
<bean id="advice" class="com.bjsxt.advice.MyAdvice"></bean>
<!--配置AOP组装-->
<aop:config>
<!--基于Aspectj方式配置-->
<aop:aspect ref="advice">
<!--声明切点-->
<aop:pointcut id="mp" expression="execution(* com.bjsxt.*.impl.*.*(..))"/>
<!--配置通知方法-->
<aop:before method="before" pointcut-ref="mp"></aop:before>
<!--切点正常执行才会被执行-->
<aop:after-returning method="after" pointcut-ref="mp"></aop:after-returning>
<!--切点是否正常执行都会执行-->
<!--<aop:after method="after" pointcut-ref="mp"></aop:after>-->
<aop:around method="round" pointcut-ref="mp"></aop:around>
<!-- 必须使用throwing声明异常参数名 -->
<aop:after-throwing method="myThrow" pointcut-ref="mp" throwing="ex"> </aop:after-throwing>
</aop:aspect>
</aop:config>
</beans>
注意:
after和after-returning,after无论切点是否出现异常都执行的后置通知,after-returning只有在切点正常执行完 成,才会触发的通知。