1.创建自定义注解来声明自定义注解
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface DateConvert {
String value() default "";
}
@Target:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(SOURCE<CLASS<RUNTIME)
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
2.使用spring aop 来使用自定义注解
@Pointcut("@annotation(com.asiainfo.config.DateConvert)")
private void Pointcut() {}
//将注解中切点的注解和传入增强方法中的注解的参数名称保持统一;
//@Before和@After不不支持ProceedingJoinPoint,
//需要将ProceedingJoinPoint换成JoinPoint,而接口ProceedingJoinPoint继承了JoinPoint接口
@Around(value = "Pointcut()&&@annotation(dateConvert)")
public Object modifyArgs(ProceedingJoinPoint joinPoint, DateConvert dateConvert) {
//获取参数,可在此修改参数
Object[] args = joinPoint.getArgs();
for(int i=0;i<args.length;i++){
System.out.println(args[i]);
JSONObject jsonObject= JSON.parseObject(JSONObject.toJSONString(args[i]));
System.out.println(jsonObject.keySet());
System.out.println(jsonObject.getString("username"));
}
System.out.println("注解作用的方法名: " + joinPoint.getSignature().getName());
System.out.println("所在类的简单类名: " + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("所在类的完整类名: " + joinPoint.getSignature().getDeclaringType());
System.out.println("目标方法的声明类型: " + Modifier.toString(joinPoint.getSignature().getModifiers()));
return null;
}
JoinPoint 方法
- 注解作用的方法名
joinPoint.getSignature().getName()
- 所在类的简单类名
joinPoint.getSignature().getDeclaringType().getSimpleName()
- 所在类的完整类名
joinPoint.getSignature().getDeclaringType()
- 目标方法的声明类型
Modifier.toString(joinPoint.getSignature().getModifiers())
3.测试
- 测试类
@RestController
@RequestMapping("/authUser")
public class AuthUserController {
@Autowired
private RedisClientService redisClientService;
@Autowired
private AuthUserServiceImpl authUserService;
@DateConvert(value = "测试测试测试")
@GetMapping("/test")
public String test(@RequestParam Map map){
return "123";
}
- 调用
http://127.0.0.1:8889/device-monitor/authUser/test?username=zhangdan&age=2
- 结果