Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading Nested Placeholders from Properties File with Spring

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

like image 727
lase Avatar asked Jan 04 '13 16:01

lase


People also ask

How to use property placeholder in spring boot?

Spring Boot - Using ${} placeholders in Property Files We just need to use ${someProp} in property file and start the application having 'someProp' in system properties or as main class (or jar) argument '--someProp=theValue'. This feature allows us to use 'short' command line arguments.

What is Property placeholder in spring?

The context:property-placeholder tag is used to externalize properties in a separate file. It automatically configures PropertyPlaceholderConfigurer , which replaces the ${} placeholders, which are resolved against a specified properties file (as a Spring resource location).

What are the ways in which spring boot can read configurations?

Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration.


1 Answers

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.

like image 97
Tom McIntyre Avatar answered Nov 10 '22 16:11

Tom McIntyre