Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

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.