俯拾皆是的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兩個屬性
// 運行時生效,可應(yīng)用于類、接口或者枚舉
@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統(tǒng)一管理
@Aspect
@Component
public class MyLogAspect {
// 配置織入點
@Pointcut("@annotation(MyLog)")
private void logPointCut(){}
// 環(huán)繞織入,在調(diào)用方法的前后執(zhí)行
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
// 獲取方法名稱
MethodSignature signature =(MethodSignature) joinPoint.getSignature();
String methodName=signature.getName();
// 獲取注解MyLog的參數(shù)值
Method method = signature.getMethod();
MyLog myLog=method.getAnnotation(MyLog.class);
String level=myLog.level();
// 打印日志
System.out.println("方法名為:"+methodName+",日志級別為:"+level);
long start = System.currentTimeMillis();
// 注解方法繼續(xù)執(zhí)行
Object result=joinPoint.proceed();
System.out.println("方法的執(zhí)行時間為:" + (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
推薦閱讀:
評論
圖片
表情
