Jul 8, 2024
Laptop class with a compile method
public void compile() {
System.out.println("Compiling with 44 bugs");
}
Laptop object in main class to call compile methodnew keyword is not ideal@Component to mark classes for Spring to manage and instantiate@Component
public class Laptop {
// methods
}
@Autowired to automatically wire dependencies
@Autowired
private Laptop laptop;
@Autowired on fields@Autowired on the constructor or omit since it's the defaultpublic Dev(@Autowired Laptop laptop) {
this.laptop = laptop;
}
@Autowired on setter methods@Autowired
public void setLaptop(Laptop laptop) {
this.laptop = laptop;
}
Computer which Laptop and Desktop implement
interface Computer {
void compile();
}
Computer type for dependencies instead of specific Laptop/Desktop
@Autowired
private Computer computer;
@Primary
@Primary
@Component
public class Laptop implements Computer {
// methods
}
@Qualifier
@Autowired
@Qualifier("laptop")
private Computer computer;
@Primary and @QualifierPractical Tips
@Primary sparingly, only when dealing with multiple beans@Qualifier for more specific bean resolution needs