2019独角兽企业重金招聘Python工程师标准>>>

在做电信的项目过程中,遇到根据可配置的短信模板去适配相应的短信的内容。

Spring的源码提供了解析object对象的属性方法

详见:commons-beanutils-1.8

public class BeanUtilsBean {

public void copyProperties(Object dest, Object orig)
        throws IllegalAccessException, InvocationTargetException {

// Validate existence of the specified beans
        if (dest == null) {
            throw new IllegalArgumentException
                    ("No destination bean specified");
        }
        if (orig == null) {
            throw new IllegalArgumentException("No origin bean specified");
        }
        if (log.isDebugEnabled()) {
            log.debug("BeanUtils.copyProperties(" + dest + ", " +
                      orig + ")");
        }

// Copy the properties, converting as necessary
        if (orig instanceof DynaBean) {
            DynaProperty[] origDescriptors =
                ((DynaBean) orig).getDynaClass().getDynaProperties();
            for (int i = 0; i < origDescriptors.length; i++) {
                String name = origDescriptors[i].getName();
                // Need to check isReadable() for WrapDynaBean
                // (see Jira issue# BEANUTILS-61)
                if (getPropertyUtils().isReadable(orig, name) &&
                    getPropertyUtils().isWriteable(dest, name)) {
                    Object value = ((DynaBean) orig).get(name);
                    copyProperty(dest, name, value);
                }
            }
        } else if (orig instanceof Map) {
            Iterator entries = ((Map) orig).entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                String name = (String)entry.getKey();
                if (getPropertyUtils().isWriteable(dest, name)) {
                    copyProperty(dest, name, entry.getValue());
                }
            }
        } else /* if (orig is a standard JavaBean) */ {
            PropertyDescriptor[] origDescriptors =
                getPropertyUtils().getPropertyDescriptors(orig);
            for (int i = 0; i < origDescriptors.length; i++) {
                String name = origDescriptors[i].getName();
                if ("class".equals(name)) {
                    continue; // No point in trying to set an object's class
                }
                if (getPropertyUtils().isReadable(orig, name) &&
                    getPropertyUtils().isWriteable(dest, name)) {
                    try {
                        Object value =
                            getPropertyUtils().getSimpleProperty(orig, name);
                        copyProperty(dest, name, value);
                    } catch (NoSuchMethodException e) {
                        // Should not happen
                    }
                }
            }
        }

}

}

于是自己写了一个工具类:

 * @author liukang* */public class BeanPropertiesUtils
{/*** 获取对象的属性* @param object* @return*/public static Map<String,Object> getProperties(Object object){      Map<String,Object> ps = new HashMap<String, Object>();PropertyDescriptor[]  propertyDescriptors = BeanUtils.getPropertyDescriptors(object.getClass());for(PropertyDescriptor propertyDescriptor:propertyDescriptors){Method readMethod = propertyDescriptor.getReadMethod();try{if(readMethod!=null){if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {readMethod.setAccessible(true);}Object value = readMethod.invoke(object);          ps.put(propertyDescriptor.getName(),value);}}catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();System.out.println(propertyDescriptor.getName());}   }return ps;}
}

可以根据短信模板去适配相应的属性值

 protected  String createSmsFromTemplate(String smsTemplate,Object object){Map<String,Object>  ps = BeanPropertiesUtils.getProperties(object);Iterator it =  ps.entrySet().iterator();String returnSmsTemplate = smsTemplate;while (it.hasNext()) {Map.Entry<String,Object> entry = (Map.Entry) it.next();StringBuilder  smsNeedReplace = new StringBuilder(); smsNeedReplace.append("{");smsNeedReplace.append(entry.getKey());smsNeedReplace.append("}");StringBuilder smsWillReplace = new StringBuilder();smsWillReplace.append(entry.getValue());returnSmsTemplate = StringUtils.replace(returnSmsTemplate, smsNeedReplace.toString(), smsWillReplace.toString());}return returnSmsTemplate;}

短信模板:

String smsRewardTemplet = "Congratulations! Your lucky draw number {betNumber} is a winning number of {productName} on {periods}! Your reward of {smsRewardMoneySymbol} will be sent to  {winnerNumber} CooBill basic account.";

构造短信模板想要的实现类:

public class LotteryRecord  implements Serializable {/*** */private Date betTime; // 投注时间private String betNumber; // 投注号码private Double betMoney; // 投注金额private Date lotteryOpenTime; // 开奖时间private Integer lotteryResult = 0; // 开奖结果:0 未开奖 1 未中奖 2 中奖private Double winMoney; // 中奖金额private Double actualGrantMoney; // 实发奖金......
}

将自己需要的短信里面的值作为对象的属性值,短信里面的值和对象的属性名称同名

测试类:

@Testpublic void testSmsTemplets(){LotteryRecord lotteryRecord=new LotteryRecord();lotteryRecord.setBetNumber("4917");lotteryRecord.setProductName("lottery");lotteryRecord.setPeriods("2161020");lotteryRecord.setSmsRewardMoneySymbol("10.00");lotteryRecord.setActualGrantMoney(12.12d);lotteryRecord.setAgentedNumber("0050529250784");lotteryRecord.setAgentedRemark("测试");lotteryRecord.setBetId("betId");lotteryRecord.setBetMoney(11.11);lotteryRecord.setBetMoneyType(1);lotteryRecord.setBetTime(new Date());lotteryRecord.setSmsWinnerNumber("0050568802221");lotteryRecord.setCheckAgentedNum("测试");//String smsRewardTemplet = "Congratulations! Your lucky draw number {betNumber} is a winning number of {productName} on {periods}! Your reward of {smsRewardMoneySymbol} will be sent to your CooBill basic account.";String smsRewardTemplet = "Congratulations! Your lucky draw number {betNumber} is a winning number of {productName} on {periods}! Your reward of {smsRewardMoneySymbol} will be sent to  {winnerNumber} CooBill basic account.";String smsProxyemplet = createSmsFromTemplate(smsRewardTemplet, lotteryRecord);System.out.println(smsProxyemplet);}

测试结果:

短信模板:

Congratulations! Your lucky draw number {betNumber} is a winning number of {productName} on {periods}! Your reward of {smsRewardMoneySymbol} will be sent to  {smsWinnerNumber} CooBill basic account.

Congratulations! Your lucky draw number 4917 is a winning number of lottery on 2161020! Your reward of 10.00 will be sent to  0050568802221 CooBill basic account.

这样就可以动态去适配替换内容

转载于:https://my.oschina.net/LiuLangEr/blog/777612

使用Spring获取JavaBean的属性值匹配短信模板相关推荐

  1. Spring获取JavaBean的xml形式和注解形式

    Spring获取JavaBean的xml形式和注解形式 文章目录 一.用xml文件方式管理JavaBean 1. 创建一个xml配置文件 2. 将一个Bean交由spring创建并管理 3. 获取Sp ...

  2. java获取object属性值_java反射获取一个object属性值代码解析

    有些时候你明明知道这个object里面是什么,但是因为种种原因,你不能将它转化成一个对象,只是想单纯地提取出这个object里的一些东西,这个时候就需要用反射了. 假如你这个类是这样的: privat ...

  3. getAttribute方法在IE6/7下获取href/src属性值的问题

    IE中的getAttribute方法与其他标准浏览器有很多不同,这里记录的是获取href/src属性值时的问题. 如将href=""或href="#",预期返回 ...

  4. 点击select下拉框获取option的属性值

    select下拉框作为前端开发者应该是经常使用的,最近在项目中遇到这样的情况,点击下拉框选项,需要获取所点击的option的属性值,当时想很简单啊,给option加一个点击事件不就行了,然后就加了一下 ...

  5. 关于java通过反射 获取/修改 对象属性值的一些注意事项

    getFields()与 getDeclaredFields() 前者能够获取所有public字段,包括父类字段: 后者可以所有public/protected/private类型的字段,但是不包括父 ...

  6. matplotlib之pyplot模块——获取/设置对象属性值(setp()、getp/get())

    当前有效matplotlib版本为:3.4.1. 概述 pyplot模块提供了获取/设置对象属性值的接口.功能类似于Python内置函数getattr和setattr.从源码上来看,get()是get ...

  7. SDK中配置工业相机参数时,如何在MVS中获取需要的属性值?

    SDK中配置工业相机参数时,如何获取需要的属性值? – MVS 采用SDK配置工业相机参数的时候,需要知道参数的类型,最大/小值以及步进值等,否则可能会出现各种错误,现针对常见参数的查看方法进行说明( ...

  8. 使用onclick()事件以及this获取当前标签属性值的问题

    使用onclick()事件以及"this"获取当前标签属性值的问题 代码: 效果图: 进行操作时点击对应的button需要获取其对应的id值,类.ID选择器并不适用与获取动态的数据 ...

  9. jQuery easyUI中LinkButton获取它的属性值

    jQuery easyUI中LinkButton获取它的属性值 LinkButton按钮如下: <a id="btn" href="#" class=&q ...

最新文章

  1. Linux 网络编程详解二(socket创建流程、多进程版)
  2. 使用Docker部署Node.js中的Vue项目
  3. Python数据相关系数矩阵和热力图轻松实现
  4. [Apple开发者帐户帮助]三、创建证书(3)创建企业分发证书
  5. zShowBox (图片放大展示jquery版 兼容性好)
  6. android item弹出popupwindow recycleview_Android实现RecycleView嵌套RecycleView中的item自动循环滚动功能...
  7. Linux xmpp网络不通,Pidgin XMPP协议拒绝访问漏洞
  8. C# 父类代码动态转换子类
  9. 敏捷开发绩效管理之三:个体动力之源——同行压力(松结对编程,师徒制度,跨职能团队,绩效考核)...
  10. window下使用tail -f查看tomcat日志
  11. 脑洞大开!华为云桌面和无纸化会议系统结合会怎样?
  12. C++“(已隐式声明)--它是已删除的函数 ” “尝试引用已删除的函数”知识点MARK
  13. 机器学习技术在日常生活和商业领域的应用有哪些,主要带来了什么商业收益?
  14. 【taro】taro如何打开微信小程序
  15. H3C恢复console登录密码
  16. 数字世界,企业何以抵御勒索病毒?
  17. tp控制器进阶页面跳转重定向、
  18. USB转换芯片(用来做鼠标键盘)
  19. 被刷屏的塞尔达来了,附源码!
  20. 交换排序 java_java排序算法-交换排序

热门文章

  1. 竞拍秒购电商系统开发需求和功能架构分析
  2. 多元线性回归系数求解
  3. 怎么复制cmd显示的内容?怎么把外面的东西复制到cmd里面?
  4. Jetbrains系列软件高版本闪退问题解决
  5. mysql select @x_mysql中select * for update
  6. java button中文乱码_java解决中文乱码的几种写法
  7. openEuler 嵌入式构建
  8. Android自定义控件系列二:自定义开关按钮(一)
  9. 高赞回答:为什么高级程序员不必担心自己的技术过时?
  10. 未来哪些行业值得加入?