Another way to compose Configurations is to inject a configuration class to another one.
The configuration classes themselves are registered as beans to the Spring container. That means, we can do whatever we do with a normal spring bean. For example we can use @Autowire to have Spring to perform DI in them. In the following example we are going to inject a configuration class to another one.
Example
package com.logicbig.example;
public class Client {
private DataSourceBean dataSourceBean;
Client(DataSourceBean dataSourceBean) {
this.dataSourceBean = dataSourceBean;
}
public void showData() {
System.out.println(dataSourceBean.getData());
}
}
package com.logicbig.example;
class DataSourceBean {
public String getData() {
return "some data";
}
}
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.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Autowired
private DataSourceConfig dataSourceConfig;
@Bean
Client clientBean() {
return new Client(dataSourceConfig.dataSourceBean());
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class, DataSourceConfig.class);
context.getBean(Client.class).showData();
}
}
Outputsome data
We can also inject DataSourceBean directly to AppConfig , rather than injecting DataSourceConfig class:
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
public class AppConfig2 {
@Autowired
private DataSourceBean dataSourceBean;
@Bean
Client clientBean() {
return new Client(dataSourceBean);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class, DataSourceConfig.class);
context.getBean(Client.class).showData();
}
}
Outputsome data
Constructor-based DI in the configuration class
Starting from Spring 4.3, configuration classes also support constructor DI, please see an example here to see in what kind of scenarios we should use that feature.
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
|