@ComponentScan doesn't work in Spring boot AutoConfiguration class?

Dongqing :

I am trying to create a new starter. I have a business module, say ProjectManager, that contains some classes annotated with @Component. Following the tutorial, I created an autoconfigure module, it contains an AutoConfiguration class. Firstly, I tried to use @ComponentSan to find the beans in my business module.

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

}

But it doesn't work. I have to add additional configuration class as below:

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

And then import it into AutoConfiguration class like below:

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

}

That works. But according to the spring doc.

auto-configuration is implemented with standard @Configuration classes

So my question is, Why @ComponentScan doesn't work here ? Did I make something wrong? Or it is by design ?

emoleumassi :

you have to use the compentscan annotation into the main class. Here a sample 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);
    }
}

Cheers

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=451500&siteId=1