How can dependency injection be applied using Spring Bean?
sobes.tech AI
Answer from AI
Spring Boot supports Dependency Injection (DI) mainly in three ways:
-
Field Injection:
The most common and simple way. Using@Autowiredon a field. Not recommended for production code due to testing and encapsulation issues.// Field Injection @Service public class MyService { @Autowired private MyDependency dependency; public void doSomething() { dependency.execute(); } } -
Setter Injection:
Using@Autowiredon a setter method. Allows optional dependencies (if setter can be omitted) and easier testing.// Setter Injection @Service public class MyService { private MyDependency dependency; @Autowired public void setDependency(MyDependency dependency) { this.dependency = dependency; } public void doSomething() { dependency.execute(); } } -
Constructor Injection:
The most recommended way. Using@Autowiredon the constructor. Ensures immutability of dependencies after object creation and clearly indicates required dependencies. In Spring Boot 2.x+,@Autowiredon a single constructor can be omitted.// Constructor Injection @Service public class MyService { private final MyDependency dependency; // @Autowired is optional for a single constructor in Spring Boot 2.x+ public MyService(MyDependency dependency) { this.dependency = dependency; } public void doSomething() { dependency.execute(); } }
Spring container scans classes with annotations like @Component, @Service, @Repository, @Controller and creates Beans from them. When a Bean with @Autowired on a field, setter, or constructor detects a need for another dependency, the container searches for a suitable Bean by type and/or name and injects it. If multiple Beans match, @Qualifier can be used for clarification.