Q1. What are the types of Dependency Injection in Spring?
Spring supports three types of DI: Constructor-based injection (dependencies provided via constructor arguments), Setter-based injection (dependencies set via setter methods), and Field-based injection (using @Autowired on fields). Constructor injection is recommended for mandatory dependencies, while setter injection for optional ones.
Q2. How does constructor injection work in Spring?
In constructor injection, dependencies are provided as constructor parameters. Spring resolves these arguments by type or by name. Example using annotations:
@Component
public class MyService {
private final MyRepository repo;
@Autowired
public MyService(MyRepository repo) {
this.repo = repo;
}
}
Q3. What is the difference between constructor and setter injection?
Constructor injection ensures that all mandatory dependencies are provided at object creation, making the object immutable and easier to test. Setter injection allows optional dependencies and can be reconfigured after object creation. Constructor injection is preferred for required dependencies, setter for optional ones.
Q4. What is the @Autowired annotation used for?
@Autowired is used to automatically inject dependencies by type. It can be applied to constructors, setters, fields, or arbitrary methods. Spring's IoC container resolves the dependency and injects it. If multiple beans of the same type exist, you can use @Qualifier to specify which bean to inject.
Q5. What happens if there are multiple beans of the same type for autowiring?
If multiple beans of the same type exist, Spring throws a NoUniqueBeanDefinitionException. To resolve this, you can use @Primary to indicate the primary bean, or @Qualifier("beanName") to specify exactly which bean to inject. You can also use @Resource by name.
