Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scan all beans as if they were in the current package in Spring?

I have a Spring Boot parent project which I'm using as a dependency for customer-specific extending projects. Initially, to make sure everything else was working correctly, I set the base package for the customer project to be the same as the parent project and everything worked as expected. Once I added the Application class to a sub-package however, I started getting exceptions about missing beans and components.

For an example, the parent project has base package com.example.parent and the customer project has base package com.example.parent.customerA. At first, none of the parent beans were getting picked up, so I added @ComponentScan("com.example.parent"). I then got an exception about a missing repository bean, so I added @EnableJpaRepositories("com.example.parent"). I then got an exception about a missing entity, so I added @EntityScan("com.example.parent"), and now it's running like it was when the customer project had the same package as the parent.

Is there are a cleaner way to load all the parent project's beans and components? I'd rather have a way to configure the customer project so that everything in the parent project is loaded as if the customer project had the same base package. I'm worried that if I had to add these specific annotations for jpa repos and entities, I might not have all my bases covered with some kind of other Spring object that might be added in the future.

like image 994
mowwwalker Avatar asked Mar 11 '23 05:03

mowwwalker


1 Answers

The cleaner approach is what Alex mentioned. But if you really need your spring boot application to reside in a subpackage, you can define the base packages in the @SpringBootApplication as follows.

package com.example.parent.customer


@SpringBootApplication(scanBasePackages={"com.example.parent"})
public class SpringBootApp {
//main method
}

In this way, different projects can share common spring beans and have specific components within its subpackage.

like image 97
ameenhere Avatar answered Apr 27 '23 16:04

ameenhere