Use @configuration annotations instead of Spring bean configuration

Source: Internet
Author: User

The following is a typical spring configuration file (application-config.xml):

12345678 <beans        <beanid="orderService" class="com.acme.OrderService"/>                 <constructor-argref="orderRepository"/>         </bean        <beanid="orderRepository" class="com.acme.OrderRepository"/>                 <constructor-arg ref="dataSource"/>         </bean</beans

Then you can use a bean like this:

12 ApplicationContext ctx = newClassPathXmlApplicationContext("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 @Configurationpublicclass ApplicationConfig {           public@BeanOrderService orderService() {                 returnnewOrderService(orderRepository());                   public@BeanOrderRepository orderRepository() {                 returnnewOrderRepository(dataSource());                    public@BeanDataSource dataSource() {                 // instantiate and return an new DataSource …         

Then you can use a bean like this:

12 JavaConfigApplicationContext ctx = newJavaConfigApplicationContext(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

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.