SpringBoot启动后,如何动态修改bean的信息(类似ZooKeeper,Apollo等远程配置中心)

package com.lixiao.stydy.config;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @author lx
 * 远程注册配置
 * @date 2023-09-05 13:42:47
 * ZooKeeper,Apollo,SpringClod 等注册中心动态刷新ben的值的原理
 * ApplicationEventPublisher  发布事件
 * ApplicationListener  监听事件
 * 然后通过反射设置bean的值
 */
@Component
public class RemoteRegisterConfig implements ApplicationContextAware, ApplicationRunner, ApplicationEventPublisher, ApplicationListener<RemoteRegisterConfig.YearsAddEvent> {



    @Bean("Tom")
    public Cat setCat(){
        return new Cat("Tom",1);
    }

    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000*3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Tom`s infomation is:");
                Cat tom = (Cat)applicationContext.getBean("Tom");
                System.out.println(JSON.toJSONString(tom));
                System.out.println("Years add 1");
                publishEvent(new YearsAddEvent(new Cat("Tom",2)));
                try {
                    Thread.sleep(1000*3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Year`s add 1 later Tom`s infomation is:");
                Cat tom2 = (Cat)applicationContext.getBean("Tom");
                System.out.println(JSON.toJSONString(tom2));
            }
        }).start();

    }

    @Override
    public void publishEvent(ApplicationEvent event) {
        applicationContext.publishEvent(event);
    }

    @Override
    public void publishEvent(Object event) {

    }

    @Override
    public void onApplicationEvent(YearsAddEvent event) {
        System.out.println("监听到的event是:"+JSON.toJSONString(event));
        System.out.println("监听到的event是:"+JSON.toJSONString(event));
        Cat cat = event.getCat();
        Class<? extends Cat> aClass = cat.getClass();
        Field[] catFields = aClass.getDeclaredFields();

        Class<?> tomClass = applicationContext.getType("Tom");
        Field[] declaredFields = tomClass.getDeclaredFields();
        Object tom = applicationContext.getBean("Tom");

        for (Field field : declaredFields) {
            for (Field catField : catFields) {
                if(field.getName().equals(catField.getName())){
                    catField.setAccessible(true);
                    try {
                        setFieldData(field, tom, catField.get(cat));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    }

    /**
     * 通过反射设置值
     */
    private void setFieldData(Field field, Object bean, Object obj) throws Exception {
        field.setAccessible(true);
        String data = String.valueOf(obj);
        Class<?> type = field.getType();
        if (type.equals(String.class)) {
            field.set(bean, data);
        } else if (type.equals(Integer.class)) {
            field.set(bean, Integer.valueOf(data));
        } else if (type.equals(Long.class)) {
            field.set(bean, Long.valueOf(data));
        } else if (type.equals(Double.class)) {
            field.set(bean, Double.valueOf(data));
        } else if (type.equals(Short.class)) {
            field.set(bean, Short.valueOf(data));
        } else if (type.equals(Byte.class)) {
            field.set(bean, Byte.valueOf(data));
        } else if (type.equals(Boolean.class)) {
            field.set(bean, Boolean.valueOf(data));
        } else if (type.equals(Date.class)) {
            field.set(bean, new Date(Long.valueOf(data)));
        }
    }


    /**
     * 设置applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 配置类
     */
    @Data
    class Cat{

        public Cat(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public Cat() {
        }

        private String name;
        private Integer age;
    }

    /**
     * 处理的事件
     */
    class YearsAddEvent extends ApplicationEvent {

        public Cat getCat() {
            return cat;
        }

        public void setCat(Cat cat) {
            this.cat = cat;
        }

        private Cat cat;
        /**
         * Create a new ApplicationEvent.
         *
         * @param source the object on which the event initially occurred (never {@code null})
         */
        public YearsAddEvent(Object source) {
            super(source);
            this.cat = (Cat) source;
        }
    }


}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值