經過自定義註解,在運行時爲Bean字段賦值

建立自定義註解測試

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conf {
    String value() default "";
}

未業務類配置註解this

@Component
public class DemoBean {

    @Conf(value = "id")
    private String id;

    @Conf("isOk")
    private Object isOk;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Object getIsOk() {
        return isOk;
    }

    public void setIsOk(Object isOk) {
        this.isOk = isOk;
    }
}

經過反射獲取註解屬性字段,並進行運行時賦值code

public static Object getInstance() throws IllegalAccessException, InstantiationException {
        Class<DemoBean> clz = DemoBean.class;
        Object obj = clz.newInstance();

        Field[] fields = clz.getDeclaredFields();
        for (Field field : fields) {
            boolean filedHasAnno = field.isAnnotationPresent(Conf.class);
            if (filedHasAnno) {
                field.setAccessible(true);

                Conf annotation = field.getAnnotation(Conf.class);
                Object value = annotation.value();
                if (value.equals("id")) {
                    field.set(obj, "xxx");
                } else if (value.equals("isOk")) {
                    field.set(obj, true);
                }
            }
        }
        return obj;
    }

測試圖片

DemoBean bean = (DemoBean) ConfUtil.getInstance();
            System.out.println("id: " + bean.getId());
            System.out.println("isOk: " + bean.getIsOk());

結果get

id: xxx
isOk: true

應用it

能夠作成配置中心運行時實時配置獲取賦值。io

輸入圖片說明

相關文章
相關標籤/搜索