Preslav Rachev
Preslav Rachev

Reputation: 4003

How to load @Configuration classes from separate Jars

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?

Upvotes: 15

Views: 13647

Answers (2)

zhatian diao
zhatian diao

Reputation: 163

@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

Upvotes: 9

Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22506

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

Upvotes: 17

Related Questions