使用Spring从Properties文件加载嵌套占位符 [英] Loading Nested Placeholders from Properties File with Spring

查看:327
本文介绍了使用Spring从Properties文件加载嵌套占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从属性文件中加载嵌套占位符?我正在尝试动态加载URL。

Is it possible to load nested placeholders from within a properties file? I am trying to load a URL dynamically.

例如,如果我的属性文件包含

For instance, if my properties file contains

my.url=http://localhost:8888/service/{nestedProperty}/

有没有办法在运行时加载{nestedProperty}的值?类似于ResourceBundle的行为。如果是这样,我将如何有效地实例化String?到目前为止我正在考虑

Is there a way to load in values for {nestedProperty} at runtime? Similar to the behavior of a ResourceBundle. If so, how would would I be able to effectively instantiate the String? So far I'm thinking

<bean id="myURLString" class="java.lang.String" scope="prototype" lazy-init="true">
    <property name="URL" value="${my.url}" />
</bean>

...但我不确定要嵌套的属性。如果可能的话,我想使用Annotations获取bean,尽管我目前有一些东西

...but I'm not sure what properties to nest. I'd like to get a bean using Annotations if possible, although I currently have something along the lines of

ctx.getBean("myURLString", String.class, new Object[] { nestedProperty} );

我在这里查看了PropertyPlaceholderConfigurer和其他几个属性文件问题,但我似乎无法理解弄清楚这是否可行。

I've looked into PropertyPlaceholderConfigurer and several other properties file questions on here, but I can't seem to figure out if this is even possible.

我还应该注意,我想从我的代码中动态加载这个嵌套属性,或者至少从那里操作它们(可能通过@PostConstruct?)

I should also note that I want to load this nested property dynamically from within my code, or at least manipulate them from there (possibly via @PostConstruct?)

推荐答案

是的可能:

my.url=http://localhost:8888/service/${nestedProperty}
nestedProperty=foo/bar/baz

在示例中添加大括号前面的美元符号并设置好!

Add in the dollar sign in front of the braces in your example and you're set!

要实际使用完全解析的属性,请执行以下操作:

To actually use the fully resolved property, do this:

@Value("${my.url}")
private String url;

Spring bean中的

in a Spring bean.

这篇关于使用Spring从Properties文件加载嵌套占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆