Spring
June 6, 2020
M01 Q28 How do you inject scalar/literal values into Spring beans?
To inject scalar/literal values into Spring Beans, you need to use @Value
annotation. @Value
annotation has only one field value
.
@Value
annotation has one field value that accepts:
- Simple value
- Property reference
- SpEL String
@Value
annotation can be used on top of:
- Field
- Constructor Parameter
- Method – all fields will have injected the same value. All of the parameters in the method will have the same value injected
- Method parameter – Injection will not be performed automatically if
@Value
is not present on method level or if@Autowired
is not present at the method level
- Annotation type
Inside @Value you can specify:
- Simple value -
@Value("John")
,@Value("true")
- Reference a property -
@Value("${app.department.id}")
- Perform SpEL inline computation -
@Value("#{'Wall Street'.toUpperCase()}")
,@Value("#{5000 * 0.9}")
,@Value("#{'${app.department.id}'.toUpperCase()}")
- Inject values into an array, list, set, map. To do this you need to implement ConversionService to convert the string from the
application.properties
to set or array.
What is the difference between $ and # in @Value expressions?
@Value
annotation supports two types of expressions:
- Expressions starting with
$
- used to reference a property in Spring Environment Abstraction - Expressions starting with
#
- SpEL expressions parsed and evaluated by SpEL