zoukankan      html  css  js  c++  java
  • 使用@Configuration注解来代替Spring的bean配置

    下面是一个典型的Spring配置文件(application-config.xml):

    1
    2
    3
    4
    5
    6
    7
    8
    <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了:

    1
    2
    ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml"); 
    OrderService orderService = (OrderService) ctx.getBean("orderService"); 

      现在Spring Java Configuration这个项目提供了一种通过java代码来装配bean的方案:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @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了:

    1
    2
    JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class); 
    OrderService orderService = ctx.getBean(OrderService.class);

      

     这么做有什么好处呢?

         1.使用纯java代码,不在需要xml

         2.在配置中也可享受OO带来的好处

         3.类型安全对重构也能提供良好的支持

         4.依旧能享受到所有springIoC容器提供的功能

     
    分类: Spring
  • 相关阅读:
    lightoj-1047
    lightoj-1044
    lightoj-1045
    lightoj-1082
    LeetCode偶尔一题 —— 19. 删除链表的倒数第N个节点
    Python 3.52官方文档翻译 http://usyiyi.cn/translate/python_352/library/index.html 必看!
    Python3 time模块
    JavaScript CSS 等前端推荐
    Python之 七级字典查询
    将Sublime Text 3设置为Python全栈开发环境(转一个链接)
  • 原文地址:https://www.cnblogs.com/yaowen/p/8621463.html
Copyright © 2011-2022 走看看