小刘的切面主要用于日志挡板。 1.首先 springboot中pom引入jar
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>2.要想把一个类变成切面类,需要两步, ① 在类上使用 @Component 注解 把切面类加入到IOC容器中 ② 在类上使用 @Aspect 注解 使之成为切面类
/** * 环绕通知:目标方法执行前后分别执行一些代码,发生异常的时候执行另外一些代码 * @return */ @Around(value="execution(* com.springboot.aop.controller.*.*(..))") public Object feignAtubAspectError(ProceedingJoinPoint jp){ String methodName = jp.getSignature().getName(); Object result = null; try { System.out.println("【进入挡板--->前置通知】:the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs())); //执行目标方法 result = jp.proceed(); System.out.println("【推出挡板--->返回通知】:the method 【" + methodName + "】 ends with " + result); } catch (Throwable e) { System.out.println("【feignAtubAspectError--->异常通知】:the method 【" + methodName + "】 occurs exception " , e); } System.out.println("【环绕通知中的--->后置通知】:-----------------end.----------------------"); return result; } }主要作用,进入切点前后都会有日志,异常也会有日志打印出来,方便排查问题
3.其余的几种注解大概介绍
3.1 @Aspect作用是把当前类标识为一个切面供容器读取
3.2 @Before 标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有
3.3 @AfterReturning
后置增强,相当于AfterReturningAdvice,方法正常退出时执行
3.4 @AfterThrowing异常抛出增强,相当于ThrowsAdvice
3.5 @Afterfinal增强,不管是抛出异常或者正常退出都会执行
3.6 @Around环绕增强,相当于MethodInterceptor
3.7 @DeclareParents引介增强,相当于IntroductionInterceptor
