5

I usually see in other codes which use final key word to inject Service Bean to Controllers, some code are not. So, what's the reason to use "final" in this. I know final variable that means it's immutable variable. I research some blogs that they say it relates to thread-safe.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233

1 Answers1

5

Use final when using constructor injection:

constructor injection lets the riskAssessor field be marked as final, indicating that it cannot be subsequently changed

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • 1
    But if I don't use final and use @Autowired in constructor and it still works normally? – Tam Huynh Thanh Dec 07 '20 at 02:15
  • @TamHuynhThanh if you use spring bean default singletone scope and write thread safe code then it will be thread safe, you don't have to mark as final – Ori Marko Dec 07 '20 at 06:52
  • 1
    @user7294900 I am still not able to quite properly understand the use case of keyword in constructor based injection. Can you please explain in a little more detail ? – humbleCodes Mar 19 '23 at 15:14