zoukankan      html  css  js  c++  java
  • Spring_Spring与IoC_第一个程序

    一、IoC

       IoC是一种概念,是一种思想,指将传统上由程序代码直接操控的对象调用权交给容器,通过容器来实现对象的装配和管理。控制反转是对对象控制权的转移,从程序代码本身反转到外部容器。

      当前IoC比较流行的两种实现方式:依赖注入(DI)和依赖查找(DL)。

      依赖注入,目前最优先的解耦方式,程序代码不做定位查询,这些工作由容器自行完成。

    二、传统开发方式的缺点

    Spring三层架构:

    1 @Test
    2     public void test01() {
    3         ISomeService service=new SomeServiceImpl();
    4         service.dosome();
    5     }

    test相当于view层,view层和service层耦合在一起,service实现类改动,view层便需要改动,耦合度高。

    三、Spring配置文件

    打开spring-framework-4.3.2.RELEASEdocsspring-framework-referencehtmlxsd-configuration.html,复制以下代码到applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!-- bean definitions here -->
    
    </beans>

    配置XML Catalog

    四、从容器中获取对象

    (1)在applicationContext.xml中注册Service

     <bean id="myservice" class="com.jmu.service.SomeServiceImpl"></bean>

    相当于

    SomeServiceImpl myService=new SomeServiceImpl();

    (2)创建容器对象,加载Spring配置文件

    1 @SuppressWarnings("resource")
    2     @Test
    3     public void test02() {
    4         //创建容器对象
    5         ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
    6         ISomeService service=(ISomeService) ac.getBean("myService");
    7         service.dosome();
    8     }

     五、ApplicationContext和BeanFactory容器的区别

    1. ApplicationContext容器在进行对象初始化时,会将其中的所有Bean(对象)进行创建;
    2. BeanFactory容器中的对象,在容器初始化时,并不会被创建,而是在真正获取该对象的时,才被创建;
      Application BeanFactory
    优点 响应速度快 不多占用系统资源
    缺点 占用系统资源(内存、cpu) 相对来说,响应速度慢
  • 相关阅读:
    无向图判断三元环
    POJ 2785 4 Values whose Sum is 0
    lower_bound和upper_bound
    2153: 2018湖南多校第二场-20180407(网络同步赛)
    前缀和、前缀积
    hdu 4686 Arc of Dream
    UVA Recurrences 矩阵相乘+快速幂
    UVA 11149 Power of Matrix 构造矩阵
    poj 1258 Agri-Net prim模板 prim与dijkstra的区别
    poj 1182 食物链 (并查集)
  • 原文地址:https://www.cnblogs.com/hoje/p/8127980.html
Copyright © 2011-2022 走看看