Spring 自定义注解(原来注解可以这么简单)

1.定义注解

@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:子类注解自动继承该注解

2.实现注解(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;
    }
}

3.使用注解

@RestController
@RequestMapping("/path")
public class UserController {

	@Autowired
	private UserService userService;

	@MyAnnotation()
	@GetMapping("/getUserById")
	public Object getUserById(@RequestParam("userId") String userId ) {
	return userService.getUserById(userId);
	}
}

完成以上配置运行起来然后调用UserController接口的getUserById,查看日志记录如下,表示成功!

yyyy-MM-dd HH:mm:ss [http-nio-8081-exec-n] INFO  com.xxx.yyy.aop.MyAnnotationAop : 请求参数:[{"userId":"1000"}]
yyyy-MM-dd HH:mm:ss [http-nio-8081-exec-n] INFO  com.xxx.yyy.aop.MyAnnotationAop : 返回结果:{"userId":"1000","userName":"张三","sex":"男","age":29}

猜你喜欢

转载自blog.csdn.net/qq_37778018/article/details/124848604