0 day streak
java / beginner
Snippet

Constructor Dependency Injection

Constructor injection is the recommended way to handle dependencies in Spring. It ensures that the class is always instantiated with its required components and allows for final fields.

snippet.java
java
1
2
3
4
5
6
7
8
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
}
spring
Breakdown
1
@Service
Tells Spring to manage this class as a Service Bean.
2
private final UserRepository repository;
The dependency is stored in a final field to ensure immutability.