Externalizing annotation driven configuration in Spring 3.0

While it’s possible to have all configuration in a bean-wiring xml file, it is more beneficial to have environment specific configuration settings in a property file outside of the application. For example, having database connection string or REST API server URL in a property file allow you to move application binary freely between dev, stage, qa and production environments. Advantages of this approach is that you have to create only one binary distribution .ear or .war archive for all of your environments. Then all environment specific configuration will be independent from application binary. Sometimes your operation engineer put the property file into shared folder on networked drive, or into home directory of the user under which application server is running. Your task as a developer to make it possible. With Spring 3 and annotation this is extremely simple process.

1. Create property file. For example, we want to keep there remote server URL we use for REST API calls. The server URL could point to qa, stage or production depending on environment our application deployed to. For example in dev I point to localhost.

server.url=http://localhost:8080/myapps/secure/register

2. Create annotation in application configuration file. I use element in the “context” configuration namespace. It could be configured like this.
Note that you can always use fully qualified resource locations instead of relative paths: e.g. “file:C:/config/services.xml” or “classpath:/config/services.xml”. However, be aware that you are coupling your application’s configuration to specific absolute locations then. It is generally preferable to keep an indirection for such absolute locations, e.g. through “${…}” placeholders that are resolved against JVM system properties at runtime.

 <context:property-placeholder 
   location="file:/${user.home}/fedlet/fedlet.properties"
   ignore-resource-not-found="true"
    ignore-unresolvable="true"
    properties-ref="defaultConfiguration"/>

    
    <util:properties id="defaultConfiguration">
        <prop key="server.url">http://api.myserver.com/apps/secure/register</prop>
    </util:properties>

3. Annotate property value in your bean using @Value property.

@Value("${server.url}")
    private  String WebServiceURL;

That it, sorry to disappoint but it is indeed simple.
Make sure your property files are found during Spring startup.

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>