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
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.