Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 349
Dongqing Avatar asked Jul 20 '16 07:07

Dongqing


1 Answers

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

like image 56
emoleumassi Avatar answered Oct 01 '22 14:10

emoleumassi