• Spring-2


    从spring-1的例子中我们可以发现,Spring相当于是一个容器。HelloWorld对象的生成方式不再是通过new的方式实现,而是从spring中间去获取。

    原来对创建对象方式    HelloWorld  obj  = new Helloworld();

    弊端: 输出生成的每一个变化可能涉及代码变化。如果此代码分散在你的项目中,输出生成的每一次变化都会让你受苦。

    使用spring以后:        HelloWorld obj = (HelloWorld) context.getBean("helloBean");

    其中context对象就是spring的容器对象,通过spring配置文件中所所定义的bean元素进行 实例化对象。

    好处:面向对象的概念,是一个很好的设计来打破系统进入一个组可重用的对象。然而,当系统变大,尤其是在Java项目,庞大的对象依赖关系将一直紧密耦合引起对象难以管理或修改。在这种情况下,可以使用Spring框架作为一个核心模块轻松高效地管理所有的对象依赖。

    当然 spring配置文件中需要先进行修改由原来的

    <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
        <bean id="helloBean" class="com.snake.core.HelloWorld">
            <property name="name" value="snake"></property>
        </bean>
    
    </beans>

    修改后

    <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
        <!-- 注释1
       <bean id="helloBean" class="com.snake.core.HelloWorld"> <property name="name" value="snake"></property> </bean>
    -->
      
      <!--注释2 <bean id="helloBean" class="com.snake.core.HelloWorld"> <property name="name" value="oop"></property> </bean>
      -->
    </beans>

    这个时候 我们可以选择在springXML文件中 取消掉注释1 或 注释2 同样的一段代码 在控制台中输出的结果不一样。

      HelloWorld obj = (HelloWorld) context.getBean("helloBean");

      obj.printHello();

    //取消注释1 输出的是:Spring  : Hello ! snake

    //取消注释2 输出的是:Spring  : Hello ! oop

    注意点:bean标签中不允许出现相同的id

    现在,只需要改变 Spring XML 文件使用不同的输出生成器。只修改 Spring XML 文件而不需要无码修改,这意味着更少的错误。

    有了Spring框架 - 这种依赖注入(DI)为对象的依赖关系管理有用的特性,使大型Java项目开发管理中更优雅的,高度灵活和便于维护

    Old soldiers never die
  • 相关阅读:
    北京Uber优步司机奖励政策(4月1日)
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(4月1日)
    成都Uber优步司机奖励政策(3月31日)
    北京Uber优步司机奖励政策(3月31日)
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(3月31日)
    uber司机已经激活了,就是还没有上传头
    优步深圳车辆准入标准降啦!6万8年粤车牌!
    开优步认识各色各样的人,人生需要这样的新鲜体验!
    Uber:中国市场两年内不考虑盈利,每年补贴10亿美金
    设置Windows开机自动启动VirtualBox虚拟机系统
  • 原文地址:https://www.cnblogs.com/open88/p/7667698.html
Copyright © 2020-2023  润新知