Spring Interview Prep 01
About @Autowired
In the context of Spring Framework (a popular Java framework), @Autowired is an annotation used for dependency injection. It tells Spring to automatically resolve and inject a bean (an object managed by the Spring container) into a class's field, constructor, or method.
How @Autowired
Works
Dependency Injection:
When Spring detects the @Autowired annotation on a field, constructor, or method, it searches for a bean that matches the type. If found, Spring injects the dependency automatically.
Bean Resolution:
By Type: Spring matches the type of the field or parameter. By Name (Optional): If multiple beans of the same type exist, Spring may use the bean name for disambiguation (using @Qualifier or bean names in the configuration).
Scope:
@Autowired can inject singleton beans, prototype beans, or beans of other scopes.
Common Usage
1. Field Injection
@Component
public class MyService {
@Autowired
private MyRepository myRepository;
public void performAction() {
myRepository.save();
}
}
2. Constructor Injection Constructor injection is the recommended approach as it supports immutability and easier testing.
@Component
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
public void performAction() {
myRepository.save();
}
}
3.Setter Injection
@Component
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}
public void performAction() {
myRepository.save();
}
}
Here is a Youtube playlist that features Spring.
I will add more to this blog series as I learn.