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

好处

  • 对原业务代码无侵入 就可以完成方法增强,增加代码的可读性和可维护性
  • 完成代码解耦,你切面方法方法名变了,被切的方法无需改动什么,
    • 如果没利用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)

示例代码

 <!--        导入aop场景启动器-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
 </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;
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值