diff --git a/Java/SpringBeanUpdate.java b/Java/SpringBeanUpdate.java new file mode 100644 index 0000000000000000000000000000000000000000..cd83907cbf4855f29d70540647c20a557c10936f --- /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; + } + } + +}