zoukankan      html  css  js  c++  java
  • 替换字符串占位符

    可以用spring提供的一个PropertyPlaceholderHelper类

    替换代码如下:

    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
            throws BeansException {
    
        StringValueResolver valueResolver = new PlaceholderResolvingStringValueResolver(props);
        BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
    
        String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
        for (String curName : beanNames) {
            // Check that we're not parsing our own bean definition,
            // to avoid failing on unresolvable placeholders in properties file locations.
            if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
                BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(curName);
                try {
                    visitor.visitBeanDefinition(bd);
                }
                catch (Exception ex) {
                    throw new BeanDefinitionStoreException(bd.getResourceDescription(), curName, ex.getMessage());
                }
            }
        }
    
        // New in Spring 2.5: resolve placeholders in alias target names and aliases as well.
        beanFactoryToProcess.resolveAliases(valueResolver);
    
        // New in Spring 3.0: resolve placeholders in embedded values such as annotation attributes.
        beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
    }

     简化

       /**
         * 
         * @param template 模板
         * @param prefix 前缀
         * @param suffix 后缀
         * @param prop 键值对
         * @return 解析好的字符串模板
         */
        public static String parseValue(String template,String prefix,String suffix,Map<String,String> prop){
            StringBuilder buf = new StringBuilder(template);
            int startIndex = template.indexOf(prefix);
            while (startIndex != -1){//找到了前缀
                int suffixIndex = buf.indexOf(suffix, startIndex);//找到后缀位置
                String key=buf.substring(startIndex+prefix.length(),suffixIndex);
    //            进行字符串替换
                buf.replace(startIndex,suffixIndex+suffix.length(),prop.get(key.trim()).toString());
                startIndex = buf.indexOf(prefix, suffixIndex);//找到下一个占位的起始位置
            }
                System.out.println(buf);
            return buf.toString();
        }
  • 相关阅读:
    C#对ListView控件的几个操作技巧
    C#用代码创建控件,以及它的鼠标事件
    C#使用ListView控件对数据进行频繁更新时,出现闪烁问题的解决办法
    C#判断某个键值是否存在于字典中
    FreeMASTER 2.0的安装与使用
    C和C++中获取二维数组的行列数
    Python中类的定义和使用
    Python创建字典和添加键值
    C#用鼠标滚轮控制控件大小,实现滚轮缩放效果
    C#中对Excel文件执行写数据操作
  • 原文地址:https://www.cnblogs.com/dongma/p/10274836.html
Copyright © 2011-2022 走看看