How do constructor calls with @Autowired work?

后端 未结 3 1545
北恋
北恋 2021-02-05 15:52

I\'m learning the Spring Boot framework and I want to understand how the @Autowired annotation works. I know that in Spring Boot we have a context, and inside that

3条回答
  •  有刺的猬
    2021-02-05 15:57

    Since MyService has a @Service annotation, Spring will instantiate it automatically (i.e. register it as a bean).

    While creating it, it scans the constructors of the class and sees that a no-args constructor is defined, which is the only constructor so it will use it.

    Since it creates the service by calling your no-args constructor it found, your code at the place of "//do something" will be executed.

    On the other side, if you wouldn't have added this constructor, the MyService class would implicitly have an empty non-args constructor defined, so Spring would take the empty constructor. But in your case, you have defined an explicit constructor (which overrides the implicit empty no-args constructors) so Spring sees it as the only constructor available and there are no ambiguities.

    Long story short -> if you have one constructor defined, Spring will always use it automatically to create the bean.

    P.S: You can also have a constructor with parameters if you use the @Autowired annotation. On this case, Spring will call this constructor to create the bean and pass the required parameters if there are such beans declared that can be autowired into the constructor.

提交回复
热议问题