@Before 前置通知 目标方法之前执行
@After - 后置通知 目标方法之后执行
@AfterReturning 返回后通知:执行方法结束前通知(异常不执行)
@AfterThrowing 异常通知 :出现异常时候执行
@Around 环绕通知:环绕目标方法执行
测试示例代码
package com.roy.aop; public interface DivideService { int div(int x, int y); }
package com.roy.aop; import org.springframework.stereotype.Service; @Service public class DivideServiceImpl implements DivideService { @Override public int div(int x, int y) { int result = x / y; System.out.println(" DivideServiceImpl 被调用,测试结果为 >>>>" + result); return result; } }
package com.roy.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; @Aspect @Component public class MyAopAsepct { @Before("execution(public int com.roy.aop.DivideServiceImpl.*(..))") public void beforeNotify() { System.out.println(" ******************@Before 我是前置通知 MyAopAsepct"); } @After("execution(public int com.roy.aop.DivideServiceImpl.*(..))") public void afterNotify() { System.out.println(" ******************@After 我是后置通知 "); } @AfterReturning("execution(public int com.roy.aop.DivideServiceImpl.*(..))") public void afterReturningNotify() { System.out.println(" ******************@AfterReturning 我是返回后通知 "); } @AfterThrowing("execution(public int com.roy.aop.DivideServiceImpl.*(..))") public void afterThrowingNotify() { System.out.println(" ******************@AfterThrowing 我是异常通知 "); } @Around("execution(public int com.roy.aop.DivideServiceImpl.*(..))") public Object aroundNotify(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Object rev = null; System.out.println("我是环绕通知之前 AAA "); rev = proceedingJoinPoint.proceed(); System.out.println("我是环绕通知之后 BBB "); return rev; } }
package com.roy.aop; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootVersion; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.SpringVersion; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) public class TestAop { @Autowired private DivideService divideService; @Test public void testAopAs() { System.out.println(" Spring 的版本 " + SpringVersion.getVersion() + "\t" + " >>> Spring Boot 版本" + SpringBootVersion.getVersion()); divideService.div(10, 0); } }
执行结果对比




