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}

  • 19
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值