背景
最近以前的同事遇到这样一个问题:
需求:对于系统提供的接口有些需要登陆验证,有些则不需要验证,通过代码实现此功能。
说明:系统使用的是springboot框架,采用Java+kotlin混合编码。
方案一:利用Spring AOP实现
1. 定义自定义登录验证注解
定义自定义登录注解LoginCheck,只能添加到方法上。
@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginCheck {
}
2. 编写登录验证AOP处理器
使用spring aop对添加了LoginCheck注解的方法做切面,采用around方式对指定方法做登录验证。
@Aspect
@Component
@Slf4j
public class LoginAop {
@Pointcut("@annotation(LoginCheck)")
public void pointcut(){}
@Around("pointcut()")
public Object aop(ProceedingJoinPoint point){
try {
// 登录校验逻辑(省略)
return point.proceed();
} catch (Throwable throwable) {
log.error("error:",throwable);
}
return null;
}
}
3. 对需要添加登录验证的接口做改造
@RestController
@RequestMapping("/test")
class TestController (
val goodsService: GoodsService
){
@GetMapping("demo01")
@LoginCheck
fun demo01(){
goodsService.getOne();
}
}
4. 启动验证,程序报错了
可以看到原来kotlin的类默认是final类型的,而Spring对于类做Aop,采用的方案是使用Cglib动态生成代理