'Field required a bean of type that could not be found.' error spring restful API using mongodb
Solved it. So by default, all packages that falls under @SpringBootApplication
declaration will be scanned.
Assuming my main class ExampleApplication
that has @SpringBootApplication
declaration is declared inside com.example.something
, then all components that falls under com.example.something
is scanned while com.example.applicant
will not be scanned.
So, there are two ways to do it based on this question. Use
@SpringBootApplication(scanBasePackages={"com.example.something", "com.example.application"})
That way, the application will scan all the specified components, but I think what if the scale were getting bigger ?
So I use the second approach, by restructuring my packages and it worked ! Now my packages structure became like this.
src/├── main/│ └── java/| ├── com.example/| | └── Application.java| ├── com.example.model/| | └── User.java| ├── com.example.controller/| | ├── IndexController.java| | └── UsersController.java| └── com.example.service/| └── UserService.java└── resources/ └── application.properties
I also had the same error:
***************************APPLICATION FAILED TO START***************************Description:Field repository in com.kalsym.next.gen.campaign.controller.CampaignController required a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' that could not be found.Action:Consider defining a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' in your configuration.de here
And my packages were constructed in the same way as mentioned in the accepted answer. I fixed my issue by adding EnableMongoRepositories annotation in the main class like this:
@SpringBootApplication@EnableMongoRepositories(basePackageClasses = CustomerRepository.class)public class CampaignAPI { public static void main(String[] args) { SpringApplication.run(CampaignAPI.class, args); }}
If you need to add multiple don't forget the curly braces:
@EnableMongoRepositories(basePackageClasses = { MSASMSRepository.class, APartyMappingRepository.class })