While the simplest configuration may be expressed as a single class that exposes several beans, it is often desirable to modularize configurations for reuse and clarity.
The simplest technique for modularizing configurations is to split up
a single @Configuration
class into multiple
smaller classes:
// monolithic configuration @Configuration public class AppConfig { @Bean public ServiceA serviceA() { // ... } @Bean public ServiceB serviceB() { // ... } // assume many bean definitions follow }
The above configuration class might be supplied as a parameter to
JavaConfigApplicationContext
:
JavaConfigApplicationContext context = new JavaConfigApplicationContext(AppConfig.class); ServiceA serviceA = context.getBean(ServiceA.class); ServiceB serviceB = context.getBean(ServiceB.class);
We can easily partition this configuration such that bean definitions are spread across two classes, instead of one:
// partitioned configuration @Configuration public class AppConfigA { @Bean public ServiceA serviceA() { // ... } } @Configuration public class AppConfigB { @Bean public ServiceB serviceB() { // ... } }
Now simply supply both configuration classes to the constructor of
JavaConfigApplicationContext
:
JavaConfigApplicationContext context = new JavaConfigApplicationContext(AppConfigA.class, AppConfigB.class); // both beans are still available in the resulting application context ServiceA serviceA = context.getBean(ServiceA.class); ServiceB serviceB = context.getBean(ServiceB.class);