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 Comment

Springframework provides lots of ways to inject values into your code. What do you do when you need access to a value of something contained in a .properties file. This is so easy, but I rarely use it and always forget how to use it. This is how you define a properties:

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

The contents of the properties file is:

To inject it into a class:

    private String hostUrl;

March 14th, 2014

Posted In: Java, Spring

Tags: , ,

Leave a Comment

WP to LinkedIn Auto Publish Powered By :