Spring Certified Professional 2023 · Free Practice Question Easy
Question 8
What happens when we use @Autowired on a final field?
-
A
It returns null
-
B
It instantiates with the Object class
-
C
It instantiates with the class type
-
D
It will basically not compile
Reveal correct answer
Correct answer: D
Explanation
If you put the @Autowired annotation on a final field in Spring, it will result in an error. Spring's autowiring mechanism is not designed to inject dependencies into final fields. By default, Spring uses reflection to set the value of autowired fields, and final fields cannot be modified once they are assigned a value.
See a video explanation from my channel: https://youtu.be/WLqaVUo6QwA
See also:
Having @Autowired and final on a field are contradictory.
The latter says: that this variable has one and only one value, and it's initialized at construction time.
The former says: that Spring will construct the object, leaving this field as null (its default value). Then Spring will use reflection to initialize this field with a bean of type WorkspaceRepository.
If you want final fields autowired, use constructor injection, just like you would do if you did the injection by yourself:
- @Autowired
- public WorkspaceController(WorkspaceRepository repository) {
- this.repository = repository;
- }
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
