sen*_*sen 5 java spring spring-mvc spring-boot
我有具有以下值的属性文件。我想使用 spring mvc 读取所有具有相同前缀的属性,但不包括其他属性。
test.cat=cat
test.dog=dog
test.cow=牛
鸟=鹰
Environment.getProperty("test.cat");
Run Code Online (Sandbox Code Playgroud)
这将只返回 'cat' 。
在上面的属性文件,我想获得所有属性开始(前缀)与测试不包括鸟类。在 spring boot 中,我们可以使用 来实现这一点@ConfigurationProperties(prefix="test"),但是如何在 spring mvc 中实现相同的目标。
请参阅Spring 项目中的这个Jira 票,以解释为什么您没有看到一种方法可以做您想做的事情。可以使用最内层循环中的 if 语句进行过滤,对上述链接中的代码段进行修改。我假设您有一个Environment env变量并在寻找String prefix:
Map<String, String> properties = new HashMap<>();
if (env instanceof ConfigurableEnvironment) {
for (PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
if (propertySource instanceof EnumerablePropertySource) {
for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
if (key.startsWith(prefix)) {
properties.put(key, propertySource.getProperty(key));
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5369 次 |
| 最近记录: |