目標:創建自定義注解,實現切面編程
首先在pom文件加入:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency>
創建Annontation:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AoundAnnotation { }
創建Annontation的處理類aspect
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class AoundAnnotationAspect { /** * 此處的切點是注解的方式,也可以用包名的方式達到相同的效果 * '@Pointcut("execution(* yxm.zyf.love.service.impl.*.*(..))")' */ @Pointcut("@annotation(yxm.zyf.love.annontation.AoundAnnotation)") public void operationLog(){} /** * 環繞通知 * */ @Around("operationLog()") public boolean doAround(ProceedingJoinPoint joinPoint) throws Throwable{ boolean b=false; System.out.println("進入切面"); return (boolean)joinPoint.proceed(); //return b; } /** * 進入業務方法前 * */ @Before("operationLog()") public void doBeforeAdvice(JoinPoint joinPoint){ System.out.println("進入方法前執行....."); } /** * 處理完請求,返回內容 * @param ret */ @AfterReturning(returning = "ret", pointcut = "operationLog()") public void doAfterReturning(Object ret) { System.out.println("方法的返回值 : " + ret); } /** * 后置異常通知 */ @AfterThrowing("operationLog()") public void throwss(JoinPoint jp){ System.out.println("方法異常時執行....."); } /** * 后置最終通知,final增強,不管是拋出異常或者正常退出都會執行 */ @After("operationLog()") public void after(JoinPoint jp){ System.out.println("方法最后執行....."); } }
測試:
@RunWith(SpringRunner.class) @SpringBootTest(classes = DemoApplication.class) public class TestAnnotation { @Autowired private AnnontationServiceTestImpl a; @Test public void testA() throws Exception{ System.out.println("單元測試開始"); a.anoundTest(); System.out.println("單元測試完成"); } }