spring boot使用自定义注解做AOP

作者 : admin 本文共1089个字,预计阅读时间需要3分钟 发布时间: 2024-06-11 共1人阅读
  1. 创建一个自定注解,接收一个传值type
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EchoStatus {
    String type();
}
  1. 创建一个切面类,绑定一些切面方法,比如before,after…
@Aspect
@Component
@Slf4j
public class EchoStatusAspect {

    @Pointcut("@annotation(com.gbs.mgt.annotation.EchoStatus)")
    public void customPointcut() {
    }

    @Before("customPointcut()")
    public void beforeAdvice(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        System.out.println("Before method execution: " + joinPoint.getSignature().getName()+"入参:"+ Arrays.asList(args));
    }

    @After(value = "customPointcut()")
    public void afterAdvice(JoinPoint joinPoint) {

        System.out.println("After method execution: " + joinPoint.getSignature().getName());
    }

    @AfterReturning(value = "customPointcut()", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {

        System.out.println("After method execution: " + joinPoint.getSignature().getName()+"结果:"+result);
    }
}
@EchoStatus (type = "无所谓")
public String index(){
	return "hello word";
}
本站无任何商业行为
个人在线分享 » spring boot使用自定义注解做AOP
E-->