@Configuration
下面是一个典型的spring配置文件(application-config.xml):
<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>
然后你就可以像这样来使用是bean了:
Java代码
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml"); OrderService orderService = (OrderService) ctx.getBean("orderService");
现在Spring Java Configuration这个项目提供了一种通过java代码来装配bean的方案:
@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 … } }
然后你就可以像这样来使用是bean了:
JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class); OrderService orderService = ctx.getBean(OrderService.class);