zoukankan      html  css  js  c++  java
  • 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)));
            }
        }
    

    参考

  • 相关阅读:
    会议10
    会议09
    回忆8
    会议07
    团队报告三
    深圳展会问题关注
    移动电源频率设置
    安卓java设置字体颜色
    安卓取消默认的标题栏方法
    安卓,按钮清晰的事件注册写法
  • 原文地址:https://www.cnblogs.com/frankltf/p/11451917.html
Copyright © 2011-2022 走看看