Question

I think there are some problems when using @Value annotation and default values. I am using the following annotation on a variable. I expect to see the variable propAVar set with the property value of propA however, its always set to the default value -10

@Component
public class SomeClass {

@Value("${propA:-10}")
public String propAVar;

}

I am using PropertyPlaceholderConfigurer in the parent and child context. The child context has the context:component-scan element which scans the SomeClass. On digging into the Spring code i found the following method where the issue might lie.

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
//...
  public String resolveEmbeddedValue(String value) {
    String result = value;
    for (StringValueResolver resolver : this.embeddedValueResolvers) {
      if (result == null) {
        return null;
      }
      result = resolver.resolveStringValue(result);
    }
    return result;
  }
//...
}

Looks like resolveEmbeddedValue will go through all embeddedValueResolvers and ascertain value of that property. However, if we define a default it will look for that property in the first embeddedValueResolvers and return the default value if its not found there. Shouldn't it go through all resolvers and then return the default value? Would like to mention that this works fine without the default value.

Would be great if someone could help explain the expected behavior of @Value with default value in case of parent-child context's.

[cross-posted on spring forum]

Was it helpful?

Solution

I believe you are seeing this bug. There are some workarounds mentioned by other users in there. Also, I would suggest voting for fixing it, in case your situation is the same as the one described there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top