To separate the concerns or to achieve modularization, we can define multiple @Configuration classes. During container initialization, we can use one of the following constructors of AnnotationConfigApplicationContext
public AnnotationConfigApplicationContext(Class<?>... annotatedConfigurationClasses)
public AnnotationConfigApplicationContext(String... basePackages)
Example
Beans
class DataSourceBean {
public String getData() {
return "some app data";
}
}
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
public class Client {
@Autowired
private DataSourceBean dataSourceBean;
public void showData() {
System.out.println(dataSourceBean.getData());
}
}
Configuration classes
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DataSourceConfig {
@Bean
DataSourceBean dataSourceBean() {
return new DataSourceBean();
}
}
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
Client clientBean() {
return new Client();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class, DataSourceConfig.class);
context.getBean(Client.class).showData();
}
}
Outputsome app data
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|