替换字符串占位符

可以用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();
    }

 

posted @ 2019-01-15 23:19  冬马党  阅读(699)  评论(0编辑  收藏  举报