1. 导入jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 定义注解
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 Pass {
boolean value() default false ;
}
3. 定义切面
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Aspect
@Component
@Order(100)
public class PassAspect {
@Around("@annotation(pass)")
public Object invoked(ProceedingJoinPoint pjp, Pass pass) throws Throwable {
if(pass.value()){
pjp.proceed();
}
throw new RuntimeException("不通过");
}
}
4. 使用样例
import org.springframework.stereotype.Component;
@Component
public class Test {
@Pass(true)
void foo(){}
@Pass()
void foo1(){}
}