# spring-boot-aspect **Repository Path**: jounghu/spring-boot-aspect ## Basic Information - **Project Name**: spring-boot-aspect - **Description**: Spring Boot 自定义注解,aspect拦截 例子 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2018-08-06 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # AOP在项目中的使用 ## pom 引用 ```pom org.aspectj aspectjweaver 1.8.5 ``` ## 自定义注解 假设我们在每个方法结束后打印日志 ```java @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DisplayLog { boolean value() default false; } ``` ## 自定义切面类 `DisplayLogAspect.java` ```java @Component @Slf4j @Aspect public class DisplayLogAspect { /** * 定义切点 *

* 一种写法: execution(public * com.dobest.aspectdemo.web..*.*(..)) * 第一个*代表所有返回值类型 * 第二个*代表web包下所有的类 * 第三个*代表web包下所有类下的所有方法 * (..) 代表所有参数类型 *

* 二种写法: @annotation(com.dobest.aspectdemo.DisplaySql) * 指代哪个注解,推荐使用这种方式,自定扫描 */ @Pointcut("@annotation(com.dobest.aspectdemo.DisplaySql)") public void logAnnotation() { } /** * 方法执行完成之后 * @param joinPoint */ @After(value = "logAnnotation()") public void after(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); Annotation[] annotations = method.getAnnotations(); for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; if(annotation instanceof DisplaySql){ DisplaySql displaySql = (DisplaySql) annotation; boolean value = displaySql.value(); if(value){ log.error("method name is {}", signature.getMethod().getName()); } } } } @AfterReturning(value = "logAnnotation()", returning = "obj") public void afterReturning(JoinPoint joinPoint, Object obj) { log.error("afterReturning return value {}", obj); } } ``` `@Pointcut` 定义一个切入点 `@Before` 切点开始之前 `@Around` 切点开始之前,开始之后均会执行 `@After` 切点执行完成之后,执行 `@AfterReturning(value = "logAnnotation()", returning = "obj")` 如果执行完方法会含有返回值,这个方法会被执行