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 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 tag.


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


public class Person {

  ("${name}")
  private String name;

  //...
}

This will only work if your java beans are scanned by the same Spring context. If on different context you will need to create a separate property placeholder

Similarly you can do the same to xml bean config file


  

Multiple Environment Trick

If the value of your configuration item differ accros multiple environments (JDBC URL and context path are a good example of these), you can use the same method to inject value form environment variable.

Leave a Reply