Junior — Middle
On what criteria do you base the choice of inject in development?
sobes.tech AI
Answer from AI
The choice of dependency injection method in Java development is based on several criteria:
- Type of dependency: Constructor injection (via constructor) is preferred for mandatory dependencies as it guarantees their presence when creating an object. Setter injection is suitable for optional dependencies.
- Lifecycle management: If the object should be immutable after creation, constructor injection is better.
- Testability: Constructor injection makes testing easier as dependencies are explicitly passed.
- Framework and context: Some DI frameworks (e.g., Spring, Dagger) have their own recommendations and restrictions on injection types.
Example of constructor injection in Java using Spring:
@Component
public class Service {
private final Repository repository;
@Autowired
public Service(Repository repository) {
this.repository = repository;
}
}