Live2D

spring boot如何自定义注解

总共分三步:

1、创建一个注解

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 MyCustomAnnotation {
    String value() default ""; // 定义一个属性
}

2、创建一个使用注解的类

import org.springframework.stereotype.Service;
 
@Service
public class MyService {
 
    @MyCustomAnnotation("someValue")
    public void myMethod() {
        // 方法实现
    }
}

3、注解处理

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
 
@Aspect
@Component
public class MyCustomAnnotationAspect {
 
    @Pointcut("@annotation(MyCustomAnnotation)")
    public void myCustomAnnotationPointcut() {
    }
 
    @Around("myCustomAnnotationPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 在目标方法执行前执行的逻辑
        System.out.println("Before method execution");
        
        Object result = joinPoint.proceed(); // 执行目标方法
        
        // 在目标方法执行后执行的逻辑
        System.out.println("After method execution");
        
        return result;
    }
}

 

posted @ 2024-05-20 16:40  -涂涂-  阅读(569)  评论(0)    收藏  举报