【Spring AOP】利用AOP完成对标注了自定义注解的方法完成切面

文章目录

  • 好处
  • spring文档说明
    • Supported Pointcut Designators
    • Examples
  • 示例代码
    • 注解
    • 被切的方法
    • 切面

好处

  • 对原业务代码无侵入 就可以完成方法增强,增加代码的可读性和可维护性
  • 完成代码解耦,你切面方法方法名变了,被切的方法无需改动什么,
    • 如果没利用AOP,而是对重复逻辑抽取成方法进行调用的话,那么抽取的方法名一变,其他调用该方法的地方方法名就需要改动了
  • 将重复的操作逻辑封装在切面中,要做切面逻辑的方法只要标注一个注解即可完成切入,十分方便

spring文档说明

对自定义注解完成切面

5.1.9文档 参考

5.4. @AspectJ support — > 5.4.3. Declaring a Pointcut

Supported Pointcut Designators

@annotation: Limits matching to join points where the subject of the join point (the method being executed in Spring AOP) has the given annotation.

Examples

Any join point (method execution only in Spring AOP) where the executing method has an @Transactional annotation:

@annotation(org.springframework.transaction.annotation.Transactional)

示例代码

 
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-aopartifactId>
 dependency>

注解

YourAnnotation 可以改为你自己的注解名

import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface YourAnnotation {

    String prefix() default "";

}

被切的方法

 @YourAnnotation(key = "{key}")
    public Object testMethod(Object param) {
        log.info("目标方法运行");
       
        //你方法的业务逻辑
        return ...;
    }

切面

@Component
@Aspect
@Slf4j
public class TestAspect {


    /**
     *  环绕通知
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("@annotation(com.hyj.mall.pms.annotation.YourAnnotation)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = null;

        try {
        	//可以做一些前置处理
            log.info("切面介入工作....前置通知");
            Object[] args = point.getArgs();//获取目标方法的所有参数的值
            //拿到注解的值
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            YourAnnotation annotation = method.getAnnotation(YourAnnotation.class);

          
            //根据你的需求获取标注在注解的值 
            String key = annotation.key();
            if (args != null&&args.length>0) {
                //根据你的需求获取被切方法的args参数
            }
            //目标方法真正执行...
            result = point.proceed(args);
            //todo 根据你的实际需要,做真正的处理,
            log.info("切面介入工作....返回通知");
        }catch (Exception e) {
            log.info("切面介入工作....异常通知");
        }finally {
            log.info("切面介入工作....后置通知");
            //做一些善后工作
        }
        return result;
    }
}

你可能感兴趣的:(Spring)