俯拾皆是的Java注解,你真的get了吗?
生成文档:另外,@Documented修饰的元素将会包含在生成的Java文档中。
package com.sample.core.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 自定义一个注解,有value有desc两个属性
// 运行时生效,可应用于类、接口或者枚举
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
String value();
String desc();
}
package com.sample.core.annotation;
@MyAnnotation(value = "full-stack", desc = "欢迎来到编程世界")
public class MyClass {
}
package com.sample.core.annotation;
// 通过反射获取注解的信息
public class AnnotationTest {
public static void main(String[] args) {
Class<MyClass> myClass = MyClass.class;
MyAnnotation myAnnotation = myClass.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.value());
System.out.println(myAnnotation.desc());
}
}
package com.fullstack.commerce.user.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyLog {
// 日志级别
String level();
}
package com.fullstack.commerce.user.util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
// 这是一个切面类,同时交由Spring统一管理
@Aspect
@Component
public class MyLogAspect {
// 配置织入点
@Pointcut("@annotation(MyLog)")
private void logPointCut(){}
// 环绕织入,在调用方法的前后执行
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取方法名称
MethodSignature signature =(MethodSignature) joinPoint.getSignature();
String methodName=signature.getName();
// 获取注解MyLog的参数值
Method method = signature.getMethod();
MyLog myLog=method.getAnnotation(MyLog.class);
String level=myLog.level();
// 打印日志
System.out.println("方法名为:"+methodName+",日志级别为:"+level);
long start = System.currentTimeMillis();
// 注解方法继续执行
Object result=joinPoint.proceed();
System.out.println("方法的执行时间为:" + (System.currentTimeMillis()-start)+"毫秒。");
return result;
}
}
package com.fullstack.commerce.user.controller;
import com.fullstack.commerce.user.util.MyLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("hello")
public class HelloController {
@GetMapping("test")
@MyLog(level = "info")
public String test(){
return "Hello World";
}
}
都看到这里了,请帮忙一键三连啊,也就是点击文末的在看、点赞、分享,这样会让我的文章让更多人看到,也会大大地激励我进行更多的输出,谢谢!
https://docs.oracle.com/javase/tutorial/java/annotations/index.html
推荐阅读:
评论