Java and XML Injectable Properties on Spring

Here’s how you can create a property file which can be injected on Java classes as well as on bean XML configuration file.

Firstly ensure annotation config is switched on:


Create your properties file, in this case I create on my classpath root (src/main/resources/ on Maven-compliant project)


Register this property file on your spring context using <util:properties> tag. The file will be registered as a bean class with name config

<util:properties id="config" location="classpath:/"/>

Whenever you want to inject the value into a Java class, you can use @value annotation

public class Person {

  private String name;


Similarly you can do the same to xml bean config file

<bean class="">
  <property name="name" value="#{}"/>

Note that if you config has dots on it, you need to use the square bracket syntax or Spring will confuse the dot as property access

private String name;

Multiple Environment Trick

Another trick I love is specifying multiple environment config, eg: one for prod and dev. This is common when dealing with datasource properties:


On dev environment, I then supply -Denv=dev system property to my VM args, and do this when looking up the property:

@Value("#{systemProperties['env'] == 'dev' ? config[''] : config['dbhost']}")
private String databaseHost;

Putting String List on Properties

Property files can also hold simple string list:,

When injecting this, use the split() method. Becareful with whitespaces you placed as it will be carried over

List<String> emails;

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s