Tuesday, November 27, 2012

Autowiring optional properties with @Value

Spring provides an easy way to autowire property value into a bean. Let's say there is a system property configFileLocation. To access this property in a bean is as simple as:
@Value("#{systemProperties.configFileLocation}")
private String configFileLocation;
That's all fine and dandy. But what if the property is optional and is not always there? Spring will not like that and will let you know that by throwing:

org.springframework.beans.factory.BeanCreationException: 
Could not autowire field

And while @Autowire construct provides a required attribute, which can be set to false, alas @Value does not.

This issue is discussed in Captain Debug's Blog where he offers several work-a-rounds to this issue, but all of them seem to be quite cumbersome. So upon digging a little deeper, I stumbled on a Stack Overflow thread where one of the answers suggests following quite simple solution using SpEL Elvis operator:
@Value("#{systemProperties.getProperty('configFileLocation') ?: ''}")
private String configPath;

What this means is that if property exists, its value will be assigned to configPath, if it doesn't exist configPath will be set to blank.

3 comments:

  1. This is not as simple as you think it is.

    From your blog it requires:

    @Value("#{systemProperties.getProperty('configFileLocation') ?: ''}")

    From http://www.captaindebug.com/2012/01/autowiring-using-value-and-optional.html#.VPYBAfmsU1I it would be:

    @Value("$(configFileLocation:)")

    Less is more. The second solution wins and is pretty much readable.

    ReplyDelete
  2. I found that site very usefull and this survey is very cirious, I ' ve never seen a blog that demand a survey for this actions, very curious... palos heights real estate agents

    ReplyDelete
  3. I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information. New lenox IL Real Estate Agents

    ReplyDelete