Home >Java >javaTutorial >Why Should I Avoid Field Injection in Spring?
Field injection, as seen in the example below, arises when a bean is injected with @Autowired directly on its field:
@Component public class MyComponent { @Autowired private Cart cart; }
In contrast, constructor injection, as in the example below, involves injecting dependencies through the constructor:
@Component public class MyComponent { private final Cart cart; @Autowired public MyComponent(Cart cart){ this.cart = cart; } }
Injection Guidelines
Generally, Spring recommends the following injection practices:
Drawbacks of Field Injection
Field injection comes with several drawbacks:
Conclusion
Depending on the requirement, primarily use constructor injection or a combination of constructor and setter injection. Field injection possesses drawbacks that outweigh its convenience, making it generally inadvisable.
The above is the detailed content of Why Should I Avoid Field Injection in Spring?. For more information, please follow other related articles on the PHP Chinese website!