Dependency injection is a core concept in Spring Boot, and refers to the process of providing objects (dependencies) to a class that needs them. Dependency injection is used to decouple classes from their dependencies, which makes code more modular and easier to test.
Here is an example of dependency injection in Spring Boot:
Suppose we have a UserService class that needs to retrieve data from a UserRepository. Instead of creating a new instance of the UserRepository in the UserService class, we can use dependency injection to provide the UserRepository to the UserService.
public class UserService {
private UserRepository userRepository;
// Constructor-based dependency injection
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> getUsers() {
return userRepository.findAll();
}
}
In the example above, the UserService class has a constructor that takes a UserRepository as a parameter. When we create an instance of the UserService, we pass in a UserRepository to the constructor. This is an example of constructor-based dependency injection.
Here is an example of how we can use Spring Boot to perform dependency injection:
@Service
public class UserService {
private UserRepository userRepository;
// Constructor-based dependency injection with @Autowired
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> getUsers() {
return userRepository.findAll();
}
}
In the example above, we have annotated the UserService class with @Service, which tells Spring Boot that this class should be managed as a Spring Bean. We have also annotated the constructor with @Autowired, which tells Spring Boot to automatically provide an instance of the UserRepository when it creates an instance of the UserService. This is an example of constructor-based dependency injection using Spring Boot.
Overall, dependency injection is a powerful and flexible concept that is used extensively in Spring Boot. By decoupling classes from their dependencies, dependency injection allows us to write more modular and testable code, which is essential for building high-quality, maintainable applications.