Loading...
67

I've seen two ways to inject dependencies in Spring Boot:

__CODEBLOCK0__

Which one is recommended and why? I see field injection used a lot in tutorials but some people say it's bad practice.

asked 1 week ago
boot_dev 850

Log in to add a comment.

1 Answer

54

Constructor Injection is strongly recommended. Here's why:

Advantages of Constructor Injection:

  1. <strong>Testability</strong> - Easy to instantiate with mocks in unit tests
  2. <strong>Immutability</strong> - Can declare fields as __<em>CODE</em>BLOCK<em>3</em><strong>
  3. *<em>Null Safety</em><em> - Dependencies must be provided (can't be null accidentally)
  4. </em><em>Circular Dependency Detection</em><em> - Detected at startup, not runtime
  5. </em><em>No Reflection</em><em> - No need for @Autowired reflection
Example with Lombok: _CODE_BLOCK_0_

Field Injection problems:
_CODE_BLOCK_1_

Spring Boot 4.x+ Recommendation:*
CODEBLOCK2__

Summary: Always prefer constructor injection. Use Lombok's @RequiredArgsConstructor to reduce boilerplate.

answered 1 week ago
micro_king 1.2k
Log in to answer this question.
Question Stats
Asked: 1 week ago
Views: 2.1k
Active: 1 day ago
Related Tags