From 52532a44ea71ffa733d8f3e2533dbad20cbcad89 Mon Sep 17 00:00:00 2001 From: Yufire Date: Thu, 20 Jul 2023 11:02:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=88=91=E5=B0=B1=E4=BF=AE=E6=94=B9=E4=B8=80?= =?UTF-8?q?=E4=B8=8B=E6=88=91=E7=9A=84Bean=EF=BC=8C=E5=BE=88=E5=90=88?= =?UTF-8?q?=E7=90=86=E5=90=A7=EF=BC=8C=E4=B8=BA=E4=BB=80=E4=B9=88=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E5=B4=A9=E4=BA=86=EF=BC=9F=E5=91=9C=E5=91=9C=E5=91=9C?= =?UTF-8?q?~?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Java/SpringBeanUpdate.java | 69 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Java/SpringBeanUpdate.java diff --git a/Java/SpringBeanUpdate.java b/Java/SpringBeanUpdate.java new file mode 100644 index 0000000..cd83907 --- /dev/null +++ b/Java/SpringBeanUpdate.java @@ -0,0 +1,69 @@ +import cn.hutool.core.util.RandomUtil; +import org.apache.ibatis.reflection.MetaObject; +import org.apache.ibatis.reflection.SystemMetaObject; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +/** + * @author Yufire + * @date 2023/7/20 10:51 + * 修改一下我那可爱的Bean + */ +@Component +public class SpringBeanUpdate implements ApplicationContextAware { + + + private static final String MY_BEAN_NAME = "MyBean.java"; + + /** + * 我真的只是想修改一下我自己的bean里边的属性 + * + * @param applicationContext spring上下文对象 + * @throws BeansException 抛异常?不可能的 + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + String[] beanNameList = applicationContext.getBeanDefinitionNames(); + for (String beanName : beanNameList) { + // 判断一下bean名称是不是我的那个bean,很合理吧~ + if (!beanName.equals(MY_BEAN_NAME)) { + // 获取一下我的bean + Object beanInstance = applicationContext.getBean(beanName); + // 获取一下反射操作对象,我就喜欢用反射,强转什么的不存在 + MetaObject beanMetaObject = SystemMetaObject.forObject(beanInstance); + // 循环所有的setter方法 + for (String setterName : beanMetaObject.getSetterNames()) { + // 给我的bean覆一下值,随机值,我喜欢 + beanMetaObject.setValue(setterName, getRandomValue(beanMetaObject.getSetterType(setterName))); + } + // 打日志?不可能的 + // log.out不了("哈哈哈") + } + } + } + + /** + * 获取一个随机值 + * + * @param type 类型 + * @return 随机值 + */ + public Object getRandomValue(Class type) { + if (type.equals(String.class)) { + return RandomUtil.randomString(15); + } else if (type.equals(Integer.class)) { + return RandomUtil.randomInt(100); + } else if (type.equals(Long.class)) { + return RandomUtil.randomLong(100); + } else if (type.equals(Double.class)) { + return RandomUtil.randomDouble(100); + } else if (type.equals(Float.class)) { + return RandomUtil.randomDouble(100); + } else { + return null; + } + } + +} -- Gitee