sprinboot使用自定义注解切面
- 主要依赖
- 定义注解接口
- 定义切面
- 使用注解
- 打印切面获取参数
主要依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
定义注解接口
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LimitCount {
String name() default "";
String key() default "";
String prefix() default "";
int period() default 60;
int count() default 3;
}
定义切面
@Slf4j
@Aspect
@Component
public class LimitCountAspect {
@Pointcut("@annotation(zzc.learn.springboot.annodemo.annotation.LimitCount)")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature)point.getSignature();
Method method = signature.getMethod();
LimitCount limitCount = method.getAnnotation(LimitCount.class);
log.info("limitCount为 {}", limitCount);
Object target = point.getTarget();
log.info("调用对象:{}", target);
Object[] args = point.getArgs();
log.info("参数: {}", Arrays.toString(args));
return point.proceed();
}
}
使用注解
@Api(value = "切面注解", tags = {"切面注解"})
@RequestMapping("/anno")
@RestController
@Slf4j
public class AopAnnotationController {
@GetMapping("/login")
@ApiOperation(value = "登录", notes = "登录")
@LimitCount(key = "login", name = "登录接口", prefix = "limit")
public String login(
@RequestParam(required = true) String deviceId,
@RequestParam(required = true) String username,
@RequestParam(required = true) String password,
HttpServletRequest request) throws Exception {
if (StringUtils.equals("张三", username) && StringUtils.equals("123456", password)) {
return "登录成功";
}
return "账户名或密码错误";
}
}
打印切面获取参数
limitCount: @zzc.learn.springboot.annodemo.annotation.LimitCount(name=登录接口, count=3, period=60, prefix=limit, key=login)
调用对象: zzc.learn.springboot.annodemo.controller.AopAnnotationController@2f5fceb6
参数: [deviceId001, Tony, mypassword, org.apache.catalina.connector.RequestFacade@14e2d2f]