1、class MyAspect
package com.xml;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//@Aspect
public class MyAspect {
public void myBefore() {
System.out.println("执行前置方法");
}
public void myBefore(JoinPoint jp) {
System.out.println("执行前置方法 jp = " + jp);
}
public void myAfterReturning() {
System.out.println("执行后置通知方法");
}
public void myAfterReturning(Object result) {
System.out.println("执行后置通知方法 result = " + result);
}
public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("执行环绕通知方法:执行目标方法通知前");
Object result = pjp.proceed();
System.out.println("执行环绕通知方法:执行目标方法通知后");
if (result != null) {
result = ((String)result).toUpperCase();
}
return result;
}
public void myAfterThrowing(Exception ex) {
System.out.println("执行异常通知方法 ex = " + ex.getMessage() );
}
public void myAfter() {
System.out.println("执行最终通知方法");
}
}
2、class MyTest
package com.xml;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test01() {
String resource = "com/xml/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("mySomeService");
service.doFirst();
System.out.println("----------------------------------");
service.doSecond();
System.out.println("----------------------------------");
service.doThird();
}
}
3、applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><bean id="mySomeService" class="com.xml.SomeServiceImpl"/>
<bean id="myAspect" class="com.xml.MyAspect"/>
<!-- aop配置 -->
<aop:config>
<aop:pointcut expression="execution(* *..ISomeService.doFirst(..))" id="doFirstPointcut"/>
<aop:pointcut expression="execution(* *..ISomeService.doSecond(..))" id="doSecondPointcut"/>
<aop:pointcut expression="execution(* *..ISomeService.doThird(..))" id="doThirdPointcut"/>
<aop:aspect ref="myAspect">
<!-- 前置通知 -->
<aop:before method="myBefore" pointcut-ref="doFirstPointcut"/>
<aop:before method="myBefore(org.aspectj.lang.JoinPoint)" pointcut-ref="doFirstPointcut"/>
<!-- 后置通知 -->
<aop:after-returning method="myAfterReturning" pointcut-ref="doSecondPointcut"/>
<aop:after-returning method="myAfterReturning(java.lang.Object)" pointcut-ref="doSecondPointcut" returning="result"/>
<!-- 环绕通知 -->
<aop:around method="myAround" pointcut-ref="doSecondPointcut"/>
<!-- 异常通知 -->
<aop:after-throwing method="myAfterThrowing" pointcut-ref="doThirdPointcut" throwing="ex"/>
<!-- 最终通知 -->
<aop:after method="myAfter" pointcut-ref="doThirdPointcut"/>
</aop:aspect>
</aop:config>