【问题标题】:Spring parse property as String instead of another PropertySpring将属性解析为字符串而不是另一个属性
【发布时间】:2019-03-01 02:21:00
【问题描述】:

我有一个需要使用的现有属性文件。在那里,我必须定义一个看起来像的新属性 - ${testText1}.${testText2}

我不希望编辑这些属性,即当我实际获取这些值时,我想要 ${testText1}.${testText2} 而不是替换值。

所以我的属性文件看起来像 - someProperty=${testText1}.${testText2}

现在,当我拿到这个时:

@Value("${someProperty}")

私有字符串 myValue;

myValue 实际上应该包含字符串 - ${testText1}.${testText2} 而不是替换的值。

我该怎么做?

【问题讨论】:

    标签: java spring properties properties-file


    【解决方案1】:

    您可以通过两种方式做到这一点:

    1.定义一个新的配置类:

    @Configuration
    @ConfigurationProperties
    public class SomePropertyConfig {
    
        //name of the property from application.properties
        private String someProperty;
    
        public String getSomeProperty() {
            return someProperty;
        }
    
        public void setSomeProperty(String someProperty) {
            this.someProperty = someProperty;
        }
    }
    

    之后你可以自动装配这个bean

    @Autowired
     private SomePropertyConfig somePropertyConfig;
    

    这样,目标属性就会被注入到配置中

    1. 如果不介意修改application.properties文件,可以使用spring表达式语言。

    application.properties

     someProperty= #{'$'}{testText1}.#{'$'}{testText2}
    

    【讨论】:

    • 最好提供一些解释,说明代码为何解决/解决特定问题。
    • 用简短的描述更新了解决方案。
    • 我已经用一个例子更新了这个问题。我不希望 spring 替换值
    • #{'$'}{testText1}.#{'$'}{testText2} 为我工作,谢谢@AdinaFometescu
    • 这在我的情况下似乎不起作用 - 我最终得到相同的字符串 #{'$'}{testText1}.#{'$'}{testText2}
    猜你喜欢
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多