Spring @configuration instead of XML configuration

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.