Home >Java >javaTutorial >Why Should I Avoid Field Injection in Spring?

Why Should I Avoid Field Injection in Spring?

DDD
DDDOriginal
2024-12-08 16:26:111027browse

Why Should I Avoid Field Injection in Spring?

Understanding Field Injection and Its Avoidance

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:

  • Use constructor injection for mandatory dependencies or immutability.
  • Use setter injection for optional or changeable dependencies.
  • Avoid field injection in most cases.

Drawbacks of Field Injection

Field injection comes with several drawbacks:

  • Immutability: It precludes creating immutable objects.
  • Coupling: Classes become tightly bound to the DI container, hindering use outside of it.
  • Instantiability: Field injection requires a DI container for instantiation, limiting its use in unit testing.
  • Dependency Obscurity: Dependencies remain hidden, obscuring true dependencies.
  • Excessive Dependency Count: Field injection enables adding an excessive number of dependencies easily, potentially violating the Single Responsibility Principle.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn