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:

<context:annotation-config/>

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

name=Gerry

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:/config.properties"/>

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

@Component
public class Person {

  @Value("#{config.name}")
  private String name;

  //...
}

Similarly you can do the same to xml bean config file

<bean class="my.app.Person">
  <property name="name" value="#{config.name}"/>
</bean>

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

@Value("#{config['first.name']}")
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:

dbhost=localhost
dbhost.dev=192.168.0.20

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['dbhost.dev'] : config['dbhost']}")
private String databaseHost;

Putting String List on Properties

Property files can also hold simple string list:

emails=gerry@test.com,tom@wohoo.com

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

@Value(#{config['emails'].split(',')})
List<String> emails;
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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