The following is a typical spring configuration file (application-config.xml):
12345678 |
<
beans
>
<
bean
id="orderService" class="com.acme.OrderService"/>
<
constructor-arg
ref="orderRepository"/>
</
bean
>
<
bean
id="orderRepository" class="com.acme.OrderRepository"/>
<
constructor-arg ref="dataSource"/>
</
bean
>
</
beans
>
|
Then you can use a bean like this:
12 |
ApplicationContext ctx = new ClassPathXmlApplicationContext( "application-config.xml" ); OrderService orderService = (OrderService) ctx.getBean( "orderService" ); |
Now spring Java Configuration This project provides a scheme to assemble beans through Java code:
123456789101112131415 |
@Configuration
public
class ApplicationConfig {
public
@Bean
OrderService orderService() {
return
new
OrderService(orderRepository());
}
public
@Bean
OrderRepository orderRepository() {
return
new
OrderRepository(dataSource());
}
public
@Bean
DataSource dataSource() {
// instantiate and return an new DataSource …
}
}
|
Then you can use a bean like this:
12 |
JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig. class ); OrderService orderService = ctx.getBean(OrderService. class ); |
What's the good of doing this?
1. Use plain Java code and do not need XML
2. The benefits of OO can also be enjoyed in the configuration
3. Type safety can also provide good support for refactoring
4. Can still enjoy all the functions provided by the SPRINGIOC container
Category: Spring
Use @configuration annotations instead of Spring bean configuration