How do constructor calls with @Autowired work?

后端 未结 3 1593
北恋
北恋 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 16:03

    Long story short

    Spring will use the default constructor (the no-args constructor) to construct the components. In your example

    @Service
    public class MyService {
    
    public MyService() {
       // do something
    }
    }
    

    the constructor will be called and the // do something will be called.

    However, keep in mind that if you added a non-default constructor to the class(a constructor with arguments) then the compiler will not generate a default constructor for you and in this case, spring will fail to instantiate your MyService

    For example

      @Service
        public class MyService {
    
        public MyService(String var) {
           // do something
        }
        }
    

    will throw an exception Parameter 0 of constructor in com.example.MyService required a bean of type 'java.lang.String' that could not be found.

提交回复
热议问题