In a previous tutorial we saw how to use multiple classes by providing all @Configuration classes to the constructor of AnnotationConfigApplicationContext . That approach may not always be ideal. Often it is preferable to use an aggregation approach, where one @Configuration class logically imports the bean definitions defined by another.
The @Import annotation provides this kind of support. It is the equivalent to the <import/> element in a bean XML file.
Example
Bean classes
package com.logicbig.example;
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();
}
}
Following @Configuration class imports the above one.
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(DataSourceConfig.class)
public class AppConfig {
@Bean
Client clientBean() {
return new Client();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
context.getBean(Client.class).showData();
}
}
Outputsome app data
Multiple configurations may be imported by supplying an array of classes to the @Import annotation.
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
|