Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

A common problem is to retrieve a property from a property files and to use that value within your code. The Springframework has several tools that make that very easy to do.

The first thing to do is to create your properties file. Mine contains the following:


Next, you need to make Spring aware of the properties file. To do this, we will use the util schema. Line 4 shows that the properties has an id value. This allows us to later use that idid.key, instead of key.

<util:properties id="gsiProperties" location=""/>

Now that you have the properties available to Spring, it’s time to use them. Notice that we are using Spring Expression Language (SpEl) to inject the value(…) of the key. Normally, I would use @Autowired or @Resource(name=”…”) to inject the properties object as a map, then call get(…) on the map. SpEl gives you an additional notational choice to inject the data. @value(…) can be placed on fields, methods, method parameters and constructor parameters. Inside the @value, you can use #{…}. You do not need # for predefined variables (e.g. @value({})). If the property cannot be listed directly because it contains a period, etc, you can place it within square brackets with a single tick. An example is @Value(#{systemProperties[‘user.region’]}).

    private String igpUrl;

    private String aggregatorId;

    private String defaultSupplierId;

July 23rd, 2015

Posted In: Java, java ninja, Javaninja, SpEl, Spring

Tags: , , , ,

Leave a Reply

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

LinkedIn Auto Publish Powered By :