Return to site

🍃🎓 SPRING CERTIFICATION QUESTION: Which is a valid way to inject 'daily.limit' with @Value annotation?

· spring,vcp,java

@Value("${daily.limit}") int maxTransfersPerDay;

@Value("#{daily.limit}") int maxTransfersPerDay;

@Value("${environment['daily.limit']}") int maxTransfersPerDay;

@Value("#{environment['daily.limit']}") int maxTransfersPerDay;

#spring #certificationquestion #vcp

@Value("${daily.limit}") int maxTransfersPerDay;

and

@Value("#{environment['daily.limit']}") int maxTransfersPerDay;

${...} is the property placeholder syntax. It can only be used to dereference properties.

#{...} is SpEL syntax, which is far more capable and complex. It can also handle property placeholders, and a lot more besides.

You can use either ${daily.limit} or #{environment['daily.limit']} to retrieve the same value of the property, of course, the latter is longer but it is based on SpEL, therefore you are able to do some operations

When accessing properties, you have to be aware, that these properties are always treated as Strings.

If you take a look at the @Value("${daily.limit}"), well, this will be evaluated as a String and there will be an implicit conversion to whatever type you require.

In that example, we expect an integer so there will be an extra conversion between a string and a integer.

So you get an integer in your class, so this applies when you use an expression.

Notice that on the right-hand side, the @Value annotation uses the expression "#{environment [daily.limit']}" to inject something