记录Spring 自定义注解
一、定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
String value() default "myAnnotation";
}
只要理解和记住jdk内置的四个注解即可 (@Target,@Retention,@Documented,@Inherited)
@Retention:保留的时间范围 (RetentionPolicy)
SOURCE源文件保留(如@Override保留在源文件,编译后注解消失)
CLASS编译时保留(如lombok生成get/set)
RUNTIME运行时保留(如切面记录日志,或验证参数信息等)
@Target:使用范围 (ElementType)
packages、types(类、接口、枚举、注解类)、类成员(方法、构造方法、成员变量、枚举值)
@Documented:保留注解信息
@Inherited:子类注解自动继承该注解
二、实现注解(AOP面向切面)
@Aspect
@Component
@Slf4j
public class MyAnnotationAop {
@Pointcut("@annotation(com.xxx.yyy.annotation.MyAnnotation)")
private void pointcut(){
}
@Around(value="pointcut()")
public Object aroud(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
Object result = joinPoint.proceed(args);
log.info("请求参数:{}",JSON.toJSON(args));
log.info("返回结果:{}",JSON.toJSON(result));
return result;
}
}
三、使用注解
@RestController
@RequestMapping("/m")
public class MController {
@Autowired
private UserService userService;
@MyAnnotation()
@GetMapping("/getUserById")
public Object getUserById(@RequestParam("userId") String userId ) {
return userService.getUserById(userId);
}
}