Close

Spring Framework - @Import Examples

Spring Framework 

@Configuration
@Import(DataConfig.class)
public class AppConfig {

@Bean
@Profile(PROFILE_SWING)
public CustomerUi swingCustomerUi () {
return new SwingCustomerUi();
}

@Bean
@Profile(PROFILE_JAVA_FX)
public CustomerUi javaFxCustomerUi () {
return new JavaFxCustomerUi();
}

@Bean
public CustomerService customerService () {
return new CustomerService();
}

public static void main (String[] args) {

AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.getEnvironment()
.setActiveProfiles(PROFILE_SWING, DataConfig.PROFILE_LOCAL);
context.register(AppConfig.class);
context.refresh();

CustomerUi bean = context.getBean(CustomerUi.class);
bean.showUi();
}

public static final String PROFILE_SWING = "swing";
public static final String PROFILE_JAVA_FX = "javafx";
}
Original Post




This example shows how a configuration class can logically import other configuration.

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();
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DataSourceConfig {
@Bean
DataSourceBean dataSourceBean() {
return new DataSourceBean();
}
}
class DataSourceBean {

public String getData() {
return "some app data";
}
}
public class Client {
@Autowired
private DataSourceBean dataSourceBean;

public void showData() {
System.out.println(dataSourceBean.getData());
}
}
Original Post




See Also