Java注解+Aop
本文以实际简单需求,来整理 注解+Aop 的搭配步骤
需求:通过自定义注解拿到注解注释的东西,具体逻辑细节可忽略
环境:Springboot 2.4.3
前置准备
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
代码实现
- 定义注解
- 定义aop
定义注解
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 RateLimit {
int fieldInt() default 10;
String fieldStr() default "default";
}
定义aop并编写逻辑
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class RateLimitAop {
@Around("@annotation(rl)")
public Object around(ProceedingJoinPoint pjp, RateLimit rl){
System.out.println(pjp.getSignature().getName());
System.out.println("fieldInt >>> " + rl.fieldInt());
System.out.println("fieldStr >>> " + rl.fieldStr());
// 调用目标方法
Object proceed =null;
try {
proceed = pjp.proceed();
System.out.println("成功执行");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return proceed;
}
}
使用注解
import org.springframework.stereotype.Service;
@Service
public class UseAopService {
@RateLimit(fieldInt = 8, fieldStr = "自定义")
public void rate() {
System.out.println("run in method...");
}
}
测试类
import cn.saddydire.demo.annotest2.UseAopService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication .class)
public class AopTest {
@Resource
private UseAopService aopService;
@Test
public void test01() {
aopService.rate();
}
}