Spring-IOC使用:
IOC:控制反转
DI:依赖注入
两者关系:IOC使用依赖注入(DI)的方式,将对象的创建交给spring容器(包含并管理应用对象的配置和生命周期)中,然后调用时,直接从spring容器中获得。
Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从IOC容器中取出需要的对象。从容器中取回的对象默认是单例的,只能创建一个对象。
使用scope属性可以指定作用域:
Singleton:每个spring容器作用域中一个bean只对应一个对象实例。
Prototype:一个bean定义多个对象实例。
Request:一个bean定义作用于http request生命周期是指每个http request拥有自己的通过一个bean定义创建的实例,仅在基于web的spring applicationcontext中有效。
Session:一个bean定义作用于http session生命周期,仅在基于web的spring applicationcontext中有效。
Global:一个bean定义作用于全局的http session生命周期,仅在portlet context中使用才有效,仅在基于web的session spring applicationcontext中有效。
Application:一个bean定义作用于整个servletcontext生命周期,仅在基于web的spring applicationcontext中有效。
Pom.xml文件配置:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
</dependencies>
通过上述代码可自动导入的包:
- org.springframework:spring-aop:5.1.8.RELEASE :面向切面的编程,可以设置方法拦截器与切入点,从而将逻辑代码与实现函数分离。
- org.springframework:spring-beans:5.1.8.RELEASE:包含访问配置文件、创建和管理bean以及进行ioc/di操作的相关beanFactory.
- org.springframework:spring-context:5.1.8.RELEASE:ApplicationCotext,继承了beans特性,扩展添加国际化时间传播、资源加载和对context的创建和支持。
- org.springframework:spring-core:5.1.8.RELEASE:核心工具类
- org.springframework:spring-expression:5.1.8.RELEASE:提供表达式
- org.springframework:spring-web:5.1.8.RELEASE
Spring.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">
Spring-ioc的功能:依赖注入和控制反转(实现方式DI)
控制反转:控制获得对象的方式的反转,对象的创建转交给第三方进行,即spring容器。
Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从IOC容器中取出需要的对象。
依赖注入的方式:
方式一、基于setter方法注入
通过无参构造器或无参static工厂方法实例化bean后,调用该bean的setter方法,即可实现依赖注入。
bean配置文件:
<bean class="person" name="person">
<property name="id" value="1234"/>
</bean>
备注:其中的id是根据setter方法的名字来获得的。
方式二、基于构造方法注入
基于构造器DI,通过调用带参数的构造方法实现,每个参数代表一个依赖。
<bean class="person" name="person">
<constructor-arg name="name" value="liying"/>
方式三、复杂数据类型的依赖注入
设置空值:<null></null>
List注入:
如果属性是基本数据类型,<value标签>
<list>
<value>123</value>
<value>456</value>
</list>
如果属性是bean,使用标签<bean>
Map注入:
如果属性是基本数据类型,使用<entry key=”” value=””>
<map>
<entry key="123" value="wer"/>
<entry key="456" value="tyu"/>
</map>
如果属性是<bean>,使用<bean> value-ref