首页 > 技术文章 > spring框架ioc(控制反转)第二讲

jingyukeng 2019-01-08 20:31 原文

 配置applicationContext.xml:

springioc容器的配置文件:applicationContext.xml(默认名称)

配置schema约束:

http://www.springframework.org/schema/beans/spring-beans.xsd

配置bean

// spring的容器中获取bean实例

@Test

public void test1() {

// 创建spring容器的实例

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");

// 通过容器实例对象获取bean实例

// 通过 bean的名称来获取

CustomerDao customerDao = (CustomerDao) applicationContext.getBean("customerDao");

System.out.println(customerDao);

CustomerService customerService = (CustomerService) applicationContext.getBean("customerService");

System.out.println(customerService);

}

然后还要对bean进行实例化:

包括:通过无参构造器实例化、通过有参构造器实例化、通过静态工厂方法,这里主要介绍无参构造器实例化和静态工厂方法:

<!-- 默认通过无参构造器 -->

<bean id="customer1" class="cn.itcast.crm.domain.CstCustomer"></bean>

通过静态工厂方法:

<bean id="customer3" class="cn.itcast.crm.domain.CustomerFactory" factory-method="getCustomer"></bean>

 

DI(重点)

1.1 DI的概念

 

依赖注入(Dependency Injection:顾名思义就是在ioc容器运行期间动态的将对象的依赖关系注入到对象的属性中,没有依赖关系的不需要注入:

action:调用serviceaction依赖service,在action中所依赖的service创建被反转到spring容器。

service:依赖dao,依赖的dao创建被反转到spring容器

底层原理:spring根据配置文件中配置依赖关系,首先获取被依赖的对象dao实例,调用service对象中set方法将dao实例设置(注入)service属性。

1.2 DI测试

这里就用上面配置好的bean就好。

下面是配置依赖关系:

这里需要注意的是property标签里面的name一定要输入正确的set方法之后的字符串,ref对应依赖的对象

1.3 小结IocDi的区别

 

ioc:控制反转,将对象的创建权反转到ioc容器。

 

DI:依赖注入,将对象所依赖的对象注入到对象的属性中。

就是IOC的具体 实现方法。

 

1IOC就是一个容器

2IOC容器中包括spring管理的所有bean

3IOC容器负责对bean进行实例化

4IOC容器对bean进行实例化时候,检查有哪些依赖的属性,将依赖的属性注入到实例化的bean的属性中。

 

要实现依赖注入,需要spring管理依赖方和被依赖方(spring要对依赖方和被依赖方实例化)。

推荐阅读