直接干代码:
注解类:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLog {
}
切面类:
@Aspect
@Component
public class LogAspect {
@Around(value = "@annotation(systemLog)")
public Object checkLogin(ProceedingJoinPoint join, SystemLog systemLog) throws Throwable
{
// 获得被注解的方法的执行结果
Object ret = join.proceed();
System.out.println(JSONObject.toJSONString(ret));
// 下面是验证登录身份的逻辑代码 省略。。。。。。。
return null;
}
}
测试类:
@RestController
@RequestMapping("/test")
public class TestController {
@SystemLog
@GetMapping("/test")
public Object test(String name){
return this.getUser();
}
public User getUser() {
return new User("kuangji","1234567");
}
}
打印结果:
存在的问题:自定义的注解 只能放在test方法上,如果放在 getUser方法上 会失效,这是为什么呢?
@AfterReturning案例:
切面类:
@Aspect @Component /** * description: RetryAspect * @date: 2020/11/11 15:57 * @author: yinyu */ public class InsertRedisAop { @Pointcut("@annotation(com.thingsmatrix.securepc.device.annotation.InsertRedis)") public void retryPointCut() { } /** * 方法执行结束后 进行缓存操作 * @throws Throwable */ @AfterReturning(value = "retryPointCut() && @annotation(insertRedis)",returning = "result") public void after(InsertRedis insertRedis, Object result) { String key = insertRedis.key(); }
注解类:
@Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface InsertRedis { String key() default "6666"; }