Field Injection and Its Detriments
Field injection, whereby beans are injected via @Autowired annotations on fields, is often discouraged. To delineate this, consider the following:
@Component public class MyComponent { @Autowired private Cart cart; }
Alternatively, constructor injection employs the following approach:
@Component public class MyComponent { private final Cart cart; @Autowired public MyComponent(Cart cart){ this.cart = cart; } }
Injection Techniques
There are three primary dependency injection methods:
Field injection, as seen in the first example, corresponds to the third option.
Injection Guidelines
Spring advocates the following injection guidelines:
Drawbacks of Field Injection
Field injection is discouraged for several reasons:
Conclusion
Constructor and setter injection should be prioritized based on requirements. Field injection should generally be avoided due to its shortcomings, with convenience as its sole advantage.
The above is the detailed content of Why Should Field Injection Be Avoided in Spring Dependency Injection?. For more information, please follow other related articles on the PHP Chinese website!