spring动态修改bean

spring动态修改bean

@RequestMapping("ok")
    public Object test2(){
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        String[] beans = applicationContext.getBeanDefinitionNames();
        for (String beanName : beans) {
            // 拿到bean的Class对象
            Class<?> beanType = applicationContext.getType(beanName);
            if (beanType == null) {
                continue;
            }
            // 拿到当前bean类型的所有字段
            Field[] declaredFields = beanType.getDeclaredFields();
            if(!beanName.contains("testService") ){
                continue;
            }
            for (Field field : declaredFields) {
                // 从spring容器中拿到这个具体的bean对象
                Object bean = applicationContext.getBean(beanName);
                // 当前字段设置新的值
                try {
                    setFieldData(field, bean, "ffffff");
                    System.out.println("finished");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "ok";
    }

    private void setFieldData(Field field, Object bean, String data) throws Exception {
      // 注意这里要设置权限为true
        field.setAccessible(true);
        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)));
        }
    }

参考

posted @ 2019-09-03 11:20  技术-刘腾飞  阅读(9552)  评论(0编辑  收藏  举报