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);
}
It means:
Spring is responsible for managing the scope of objects. You don't need boilerplate like final classes with static getInstance methods. (For how singletons work in Spring see this question.)
Spring can only autowire things into the components if those components are somewhere that it has been told to look, component-scanning is how spring searches for the components that it needs to wire up. You give spring the starting points by specifying what package names it needs to start searching from. If a component is not within one of those directories, then Spring can't manage it.