Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Property Placeholders with String Concatenation

My problem looks simple but I'm not able to resolve it. I have a properties file which contains configuration details of all environments (dev, qa, prod).

Example config.properties:

dev.maxLength=2000  
qa.maxLength=4000

We have a parent Properties file which holds the host name, environment mappings.

Example hosts.properties:

host1=dev
host2=qa

The property name host1 is stored in a bean hostname.

<bean id="hostname"
  factory-bean="localhostInetAddress"
  factory-method="getHostName"/> 

To resolve the config properties name I have to join the strings as follows, ${${**hostname**}.maxLength} which should be resolved as ${dev.maxLength}

I tried using SpEL with no success. I am getting Could not resolve placeholder Exception. How can I concatenate a bean value in property place holder? How are dynamic property names constructed?

Spring version 3.2

like image 329
user2235506 Avatar asked Apr 02 '13 10:04

user2235506


People also ask

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

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 is the concatenation of string holds?

The concatenation operators combine two strings to form one string by appending the second string to the right-hand end of the first string.


2 Answers

To concatenate the values parsed from Spring property placeholders, you need to escape their values using single quoutes ('') and wrap the placeholder expressions by a SpEL expression using #{}.

<bean id="myService" class=""com.services.MyService">
  ...
  <property name="endpointAddress" value="#{'${server}' + ':' + '${port}' + '${endpoint}'}" />
</bean>

where:

server = http://domain.host.com

port = 7777

endpoint = /services/myservice

The result would be:

http://domain.host.com:7777/services/myservice

like image 105
Ghasfarost Avatar answered Sep 22 '22 10:09

Ghasfarost


I solved the issue by changing PropertyPlaceholderConfigurer beans to Properties. <util:properties/> are accessible in SpEL.

Example: "#{prop[host+'.'+'maxLength']}"

where host is a string bean.

like image 35
user2235506 Avatar answered Sep 25 '22 10:09

user2235506