-->

How to load @Configuration classes from separate J

2020-08-26 11:44发布

问题:

I have a SpringBoot main application, as well as a separate Maven module project that compiles as a separate Jar. The module has a Spring config class annotated with @Configuration, which I want to get loaded, when the main app loads.

Apparently, this does not happen out of the box (by just including the module to the main app). What else do I need to do, to get the module configuration class also get loaded by the main app?

回答1:

The easiest way is to scan the package that the @Configuration class is in.

@ComponentScan("com.acme.otherJar.config")

or to just load it as a spring bean:

 @Bean
 public MyConfig myConfig() {
     MyConfig myConfig = new MyConfig ();
     return myConfig;
 }

Where MyConfig is something like:

 @Configuration
 public class MyConfig {
     // various @Bean definitions ...
 }

See docs



回答2:

@ComponentScan annotation will scan all classes with @Compoment or @Configuration annotation.

Then spring ioc will add them all to spring controlled beans.

If you want to only add specific configurations, you can use @import annotation.

example:

@Configuration
@Import(NameOfTheConfigurationYouWantToImport.class)
public class Config {

}

@Import Annotation Doc