-1

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);
 }
climy
  • 23
  • 6
  • Welcome to Stack Overflow. Please do not include images of text that could otherwise be included in your post with proper formatting. – chb Apr 03 '19 at 16:07

1 Answers1

2

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • Thank you very much for your answer. Under the prompted to your answer, I searched the usage of @Component. The classes with this annotation are managed by spring, and the default scope of objects managed by spring is singleton. DI only can be used in those objects which are singleton objects instead of those created by new. And this is the reason that the blog says so. Do I understand correctly? – climy Apr 04 '19 at 05:37
  • @climy: i think so. Components and Beans are both spring-managed, see [Spring: component vs bean](https://stackoverflow.com/q/10604298/217324) for the difference – Nathan Hughes Apr 04 '19 at 20:12