Video in progress

Strong Junior 🌱 Spring

What is the difference between @Value("${...}") and @Value("#{...}")?

${...} is a property placeholder: the value comes from the Environment (yml, environment variables), and you can write a default after ":". #{...} is a SpEL expression: it is evaluated, and it can use other beans, methods and operators.

📖 Answer

@Value("${app.page-size:20}")                 // from a setting, 20 if absent
private int pageSize;

@Value("${app.admins}")                        // "ali,vali" -> array
private String[] admins;

@Value("#{${app.page-size:20} * 2}")           // a placeholder inside SpEL
private int maxPageSize;

@Value("#{T(java.time.Duration).ofSeconds(30)}")  // a static method
private Duration timeout;

@Value("#{priceService.defaultCurrency()}")    // another bean's method
private String currency;

What trips people up:

  • if a placeholder isn't found and there's no default, the application fails at startup with Could not resolve placeholder. That's good: the error shows up early;
  • ${app.timeout:} has an empty string as the default, which causes a conversion error if it lands in an int field;
  • @Value doesn't work on a static field: the value isn't set, and it silently stays null/0;
  • if @Value on a field is read in the constructor (with field injection), the value isn't set yet. Putting it on a constructor parameter is more correct.

Don't get carried away with SpEL: the IDE doesn't validate expressions well, and errors only show up at runtime. For many settings, @ConfigurationProperties is the clean option.