I. XML configuration Method
The following is a typical spring configuration file (application-config.xml): [XML] view plain copy <beans> <bean id= "Orderser Vice "class=" Com.acme.OrderService "/> <constructor-arg ref=" orderrepository "/> </b ean> <bean id= "orderrepository" class= "Com.acme.OrderRepository"/> <constructor-ar G ref= "DataSource"/> </bean> </beans>
Then you can use a bean like this: [Java] view plain copy applicationcontext CTX = new Classpathxmlapplicationcontext ("Applic Ation-config.xml "); OrderService OrderService = (orderservice) ctx.getbean ("OrderService");
two. @Configuration Configuration Method
Now spring Java Configuration This project provides a scheme to assemble beans through Java code:[Java] View plain copy @Configuration public class applicationconfig { @Bean public orderservice orderservice () { return new orderservice (Orderrepository ()); } @Bean public orderrepository orderrepository () { return new Orderrepository (DataSource ()); } @Bean public DataSource DataSource () &NBSp { / / instantiate and return an new datasource ... } }
Then you can use a bean like this: [Java] view plain copy javaconfigapplicationcontext CTX = new Javaconfigapplicationcontext (Applicationconfig.class); OrderService OrderService = Ctx.getbean (Orderservice.class);
three. What are the benefits of doing so?
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
Reprinted from: http://blog.csdn.net/tanksyg/article/details/8556769