Member-only story
Java Spring Quick Tip — Episode 1
2 min readMar 14, 2023
- Use constructor injection instead of @Autowire
- Constructor injection
@Component
@RequiredArgsConstructor
public class TraceFacade {
private final TraceService traceService;
public void createTrace(TraceCreateRequest traceCreateRequest) {
traceService.createTrace(TraceMapper.INSTANCE.map(traceCreateRequest));
}
}
- @Autowired injection
@Component
public class TraceFacade {
@Autowired
private TraceService traceService;
public void createTrace(TraceCreateRequest traceCreateRequest) {
traceService.createTrace(TraceMapper.INSTANCE.map(traceCreateRequest));
}
}
Constructor injection involves passing dependencies as constructor parameters, while @Autowired is a type of field injection that automatically sets the value of a field by matching it to a bean of the same type in the Spring container.
Here are some key differences between the two:
- Explicitness: Constructor injection is more explicit because the dependencies are passed as constructor parameters, making it clear what dependencies are required by the class. In contrast, field injection using @Autowired is less explicit because the dependencies are set by Spring behind the scenes.
- Testability: Constructor…