一. 前期准备
?若干自定义注解
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PayCode {
String payCode();
String name();
}
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface PayOrder {
int value() default 0;
}
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Version {
String value() default "0";
}
二. 使用自定义注解标记业务方法
@PayCode(payCode = "alia", name = "支付宝支付")
@Component
public class AliaPay {
@PayOrder(value = 1)
public void pay() {
System.out.println("===发起支付宝支付1===");
}
}
@PayCode(payCode = "jingdong", name = "京东支付")
@Component
public class JingDongPay {
@Version(value = "1.1")
public String version;
@PayOrder(value = 20)
public void pay() {
System.out.println("===发起京东支付===");
}
}
三. 原生Java获取注解
import org.springframework.boot.CommandLineRunner;
import org.springframework.util.ReflectionUtils;
@Component
public class ZTestController implements CommandLineRunner {
@Resource
private AliaPay aliaPay;
@Resource
private JingDongPay jingDongPay;
@Override
public void run(String... args) throws Exception {
PayCode aliPay = aliaPay.getClass().getAnnotation(PayCode.class);
System.out.println(aliPay);
Field versionField = ReflectionUtils.findField(jingDongPay.getClass(), "version");
Version version = versionField.getAnnotation(Version.class);
}
}
四. AnnotationUtils工具类获取
4.1 AnnotationUtils.findAnnotation获取类注解
import org.springframework.core.annotation.AnnotationUtils;
PayCode aliPay = AnnotationUtils.findAnnotation(aliaPay.getClass(), PayCode.class);
4.2 AnnotationUtils.findAnnotation获取方法注解
import org.springframework.util.ReflectionUtils;
import org.springframework.core.annotation.AnnotationUtils;
Method payMethod = ReflectionUtils.findMethod(aliaPay.getClass(), "pay");
PayOrder payOrder = AnnotationUtils.findAnnotation(payMethod, PayOrder.class);
4.3 AnnotationUtils.getValue获取注解上的指定属性值
PayCode aliPayAnnotation = AnnotationUtils.findAnnotation(aliaPay.getClass(), PayCode.class);
Object payCode = AnnotationUtils.getValue(aliPayAnnotation, "payCode");
4.4 AnnotationUtils.getAnnotationAttributes获取注解上的所有属性值
PayCode aliPay = AnnotationUtils.findAnnotation(aliaPay.getClass(), PayCode.class);
Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(aliPay);
|