I am reading a blog about DI and there are some sentences that I don't understand.
What does it mean that DI is a singleton object at runtime and only those objects within the scanning range of spring(with @Component
) can use DI by annotation(@Autowired
), while others created by new cannot use DI by annotation?
cannot use DI because Father can be created by new.
public class Father{
private SonRepository sonRepo;
private Son getSon(){return sonRepo.getByFatherId(this.id);}
public Father(SonRepository sonRepo){this.sonRepo = sonRepo;}
}
can use DI because FatherFactory is a singleton object generated by the system.
@Component
public class FatherFactory{
private SonRepository sonRepo;
@Autowired
public FatherFactory(SonRepository sonRepo){}
public Father createFather(){
return new Father(sonRepo);
}