In a Spring boot app, we tend to use @Autowire annotation, so that Spring can inject our dependency. It helps in not writing the constructor explicitly and developer doesn’t need to take care of from where this bean is coming.
At some point, we encounter errors like below:
APPLICATION FAILED TO START
Field <your-field> in com.your-package.controllers.MyController required a bean of type 'com.your-package.service.UserService' that could not be found.
The injection point has the following annotations:
Consider defining a bean of type 'com.your-package.service.UserService' in your configuration.
Probable Reasons and Solutions
@Autowire searches in the spring context for the bean.
There might be few probable reasons of this error:
You have not defined the bean anywhere (Unless you declared the class with annotations like service/component etc, see next point). If you are using xml spring context, define the bean there.
You forgot to declare the class with annotations like: @Component, @Service, @Controller, @Configuration, @Repository, there might be more
(Note: above annotations are for respective purposes, so use them as per use-case)
You have initialized the class by explicit constructor (by new), Autowire will not work there. As, that instance will not be registered to Spring for dependency injection.
So, do not initialize a class by explicit constructor. Let spring handle it for you.
You have used @ComponentScan, but in wrong package. Specify the correct package there. You can specify multiple packages there as well.
Your spring-boot main class (@SpringBootApplication), is located in some inner package. By default, spring boot main class, scans the child packages. So, if you have defined your main class in some inner package, move it to the top package.
There might be mutiple beans of same class. You need to help @Autowire, that which bean name you want to take.