Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 501
Preslav Rachev Avatar asked May 16 '15 07:05

Preslav Rachev


People also ask

Can we have multiple @configuration classes?

One configuration class can import any number of other configuration classes, and their bean definitions will be processed as if locally defined.

Which class is used to access @configuration classes from the client application?

JavaConfigApplicationContext provides direct access to the beans defined by @Configuration -annotated classes.

Can we have multiple @configuration in Spring?

You should be able to autowire them: @Configuration public class Conf2 { @Autowired Conf1 conf1; ... } Alternatively, you can autowire beans rather than configurations: @Configuration public class Conf2 { @Autowired Foo foo; ... }

What is the use of @configuration in Spring boot?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.


1 Answers

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

like image 53
Evgeni Dimitrov Avatar answered Oct 13 '22 21:10

Evgeni Dimitrov