Loading Nested Placeholders from Properties File with Spring

我怕爱的太早我们不能终老 提交于 2019-12-21 11:28:18

问题


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}/

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>

...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} );

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.

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?)


回答1:


Yes it is possible:

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;

in a Spring bean.



来源:https://stackoverflow.com/questions/14160607/loading-nested-placeholders-from-properties-file-with-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!