3.1.2 Spring之IoC

Spring之IoC

1.  IoCDI

(1) IoC

控制反转( IoC, Inversion of Control) , 是一个概念, 是一种思想。 控制反转就

是对对象控制权的转移, 从程序代码本身反转到了 外部容器。 把对象的创建、 初始化、

销毁等工作交给spring容器来做。 由spring容器控制对象的生命周期。

(2) DI

依赖注入: Dependency Injection。 依赖注入DI是指程序运行过程中, 若需要调用另

一个对象协助时, 无须在代码中创建被调用者, 而是依赖于外部容器, 由外部容器创

建后传递给程序。

依赖注入是目 前最优秀的解耦方式。 依赖注入让Spring的Bean之间以配置文件的方式

组织在一起, 而不是以硬编码的方式耦合在一起的。

(3) IoC与DI的关系

IoC是一个概念, 是一种思想, 其实现方式多种多样。 当前比较流行的实现方式之一

是DI。

2. 第一个IoC程序

(1) 导入jar包( 基本4个)

spring-beans-4.3.16.RELEASE.jar

spring-context-4.3.16.RELEASE.jar

spring-core-4.3.16.RELEASE.jar

spring-expression-4.3.16.RELEASE.jar

再放入两个日志包:

com.springsource.org.apache.commons.logging-1.1.1.jar

com.springsource.org.apache.log4j-1.2.15.jar

(2) 创建spring配置文件

1) 创建applicationContext.xml

2) spring-framework-4.3.16.RELEASE/docs/spring-framework-reference/html/

xsd-configuration.html 中找到配置文件头信息(the beans schema)

<?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的定义:以下配置相当于SomeService service = new SomeServiceImpl(); -->

<bean id="someServiceImpl" class="com.bjsxt.service.impl.SomeServiceImpl"></bean>

</beans>

3) 复制本地文件 D:\eclipse_mars2\xsd\spring-beans-4.3.xsd 到 eclipse目录

复制http://www.springframework.org/schema/beans/

spring-beans.xsd 到XML catalog中 key

(3) Bean的定义与注册

(4) spring容器中获取Bean

3. ApplicationContext容器与BeanFactory容器的区别

4. Bean的装配

Bean的装配, 即Bean对象的创建。

4. 1 默认装配方式(构造方式)

4. 2 动态工厂Bean

4. 3 静态工厂Bean

5. Bean的作用域(单态模式singleton\原型模式prototype)

猜你喜欢

转载自www.cnblogs.com/kendyho/p/10725068.html