Use constructor injection by declaring your dependency as a private final field and accepting it as a constructor parameter. Spring will create the dependency bean and pass it into the constructor automatically.
Example:
import org.springframework.stereotype.Component;
@Component
public class MyDependency {
public void doSomething() {
System.out.println("Dependency logic executed.");
}
}
import org.springframework.stereotype.Service;
@Service
public class MyService {
private final MyDependency myDependency;
public MyService(MyDependency myDependency) {
this.myDependency = myDependency;
}
public void doWork() {
myDependency.doSomething();
}
}
Spring can inject MyDependency because:
MyDependencyis a Spring bean, for example annotated with@Component.MyServiceis also a Spring bean, for example annotated with@Service.MyServicehas a constructor that requiresMyDependency.
In modern Spring, if the class has only one constructor, you usually do not need @Autowired:
@Service
public class MyService {
private final MyDependency myDependency;
public MyService(MyDependency myDependency) {
this.myDependency = myDependency;
}
}
If you use Lombok, you can make it shorter:
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class MyService {
private final MyDependency myDependency;
public void doWork() {
myDependency.doSomething();
}
}
Constructor injection is recommended because it makes dependencies explicit, allows fields to be final, improves testability, and prevents partially initialized objects.
