@ComponentScan not working in Spring AutoConfiguration boot class?

I am trying to create a new starter. I have a business module, for example ProjectManager, which contains some classes annotated with @Component. After the tutorial, I created an autoconfiguration module, it contains an AutoConfiguration class. First, I tried using @ComponentSan to find beans in my business module.

@ComponentScan(value = {"com.foo.project"}) @ConditionalOnClass({Project.class}) @Configuration public class ProjectAutoConfiguration { .... } 

But that will not work. I have to add an additional configuration class as shown below:

 @Configuration @ComponentScan(value = {"com.foo.project"}) @MapperScan(value = {"com.foo.project"}) public class ProjectConfig { } 

And then import it into the AutoConfiguration class, as shown below:

 @Import(ProjectConfig.class) @ConditionalOnClass({Project.class}) @Configuration public class ProjectAutoConfiguration { .... } 

It works. But according to spring doc .

automatic configuration is implemented with standard @Configuration classes

So my question is: why is @ComponentScan not working here? Did I do something wrong? Or is it design?

+6
source share
3 answers

you should use compentscan annotation in the main class. Here is an example code:

 @SpringBootApplication @ComponentScan("com.foo.project") public class MainApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(MainApplication.class); } public static void main(String[] args) { new MainApplication().configure(new SpringApplicationBuilder(MainApplication.class)).run(args); } } 

Greetings

+7
source

Automatically, everything requires the Application class (annotated with @SpringBootApplication) to be in a "higher" package than the components you want to scan.

Using:

 package com.example.foo; 

for your application and put the components in a package, for example:

 package com.example.foo.entities; 

See also https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html

+3
source

Can you try the following:

 @ConditionalOnClass({Project.class}) @Configuration @EnableAutoConfiguration @ComponentScan(value = {"com.foo.project"}) public class ProjectAutoConfiguration { .... } 
0
source

All Articles