Springboot 自定义注解

新增注解

package com.join.payment.core;

import java.lang.annotation.*;

/**
 * 可支付订单注解
 * @author Administrator
 */
@Target(ElementType.TYPE) // 作用于类上
@Retention(RetentionPolicy.RUNTIME) // 运行时可见
@Inherited // 可继承
@Documented // javadoc 可见
public @interface PaymentOrder {

    String value();
}

在需要的类上注解

@PaymentOrder("order")
public class MyOrder{
}
      @Target(ElementType.TYPE)  ——》接口、类
      @Target(ElementType.FIELD)   ——》属性
      @Target(ElementType.METHOD)   ——》方法
      @Target(ElementType.PARAMETER)   ——》方法参数
      @Target(ElementType.CONSTRUCTOR)  ——》构造函数
      @Target(ElementType.LOCAL_VARIABLE)  ——》局部变量
      @Target(ElementType.ANNOTATION_TYPE)  ——》注解
      @Target(ElementType.PACKAGE)   ——》包 

扫描注解类 并获得注解参数

 String basePackage = "com.ruoyi";
        Reflections f = new Reflections(basePackage);
        Set<Class<?>> set = f.getTypesAnnotatedWith(PaymentOrder.class);
        for (Class<?> c : set) {
            PaymentOrder annotation = c.getAnnotation(PaymentOrder.class);
            if (annotation !=null){
                String businessName = annotation.value();
                if(StringUtils.hasLength(businessName)){
                    this.map.put(businessName,c);
                }
            }
        }
上一篇
下一篇