Spring_Spring与IoC_第一个程序

一、IoC

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

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

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

二、传统开发方式的缺点

Spring三层架构:

Spring_Spring与IoC_第一个程序

Spring_Spring与IoC_第一个程序

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.RELEASE\docs\spring-framework-reference\html\xsd-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配置文件

Spring_Spring与IoC_第一个程序

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) 相对来说,响应速度慢