> 文档中心 > Spring5 IOC容器管理—基于XML方式

Spring5 IOC容器管理—基于XML方式

Spring IOC(控制反转)

  • 一、IOC容器
    • 1.什么是IOC
    • 2. IOC底层原理
    • 3. 图解IOC底层原理
    • 4. IOC接口
  • 二、通过IOC容器操作Bean管理—基于XML方式
    • 1.什么是IOC操作Bean管理
      • 1.1 Bean管理
      • 1.2 Bean管理操作两种实现方式
    • 2. 基于xml方式注入属性
      • 2.1 基于xml配置文件创建对象
      • 2.2 基于xml方式注入属性
      • 2.3 特殊属性(空值,特殊符号)注入
      • 2.4 注入属性—外部bean
      • 2.5 注入属性—内部bean
      • 2.7 IOC 操作 Bean 管理——xml 注入集合属性
      • 2.8 在集合里面设置对象类型值
      • 2.9 把集合注入部分提取出来
    • 3. FactoryBean
    • 4. bean作用域
    • 5. bean生命周期
    • 6. 属性自动装配
    • 7. 引入外部属性配置文件

Spring简介

一、IOC容器

1.什么是IOC

(1)控制反转,把对象创建和对象之间的调用过程,交给 Spring 进行管理
(2)使用 IOC 目的:为了耦合度降低

2. IOC底层原理

xml 解析、工厂模式、反射

3. 图解IOC底层原理

假设我们有UserService和UserDao两个类,UserService类中的execute方法需要调用UserDao类中的add()方法来完成对数据库的操作。

原始方式

如上图所示的原始方式,两个类之间的耦合度高,如果UserDao类有所改变,那还得对UserService类进行修改,不方便开发。

工厂模式

基于原始方法的不足,提出了工厂模式的设计思想,另建一个UserFactory类,以此来降低UserService和UserDao两个类之间的耦合度。

Spring5 IOC容器管理—基于XML方式

另基于工厂模式的基础,提出了IOC容器管理方式,以此来进一步降低两个类之间的耦合度。

4. IOC接口

a)BeanFactory接口:IOC容器基本实现是Spring内部接口的使用接口,不提供给开发人员进行使用(加载配置文件时候不会创建对象,在获取对象时才会创建对象。)

​ b)ApplicationContext接口:BeanFactory接口的子接口,提供更多更强大的功能,提供给开发人员使用(加载配置文件时候就会把在配置文件对象进行创建)
b方式相当于把创建对象等耗时行为都交给了启动时的服务器去做,减小运行时的开销,推荐使用方式b来加载配置文件

二、通过IOC容器操作Bean管理—基于XML方式

1.什么是IOC操作Bean管理

1.1 Bean管理

Bean管理指的是两个操作:Spring创建对象及Spring属性注入

1.2 Bean管理操作两种实现方式

基于XML配置文件方式实现 本篇
基于注解方式实现

2. 基于xml方式注入属性

2.1 基于xml配置文件创建对象

<bean id="user" class="com.spring01.User"></bean>

2.2 基于xml方式注入属性

a) 使用set方法进行属性注入

public class Book {     //创建属性     private String bname;   public Book(String bname){     this.bname = bname;     }     //创建属性对应的set方法     public void setBname(String bname) {  this.bname = bname;     }}
<bean id="book" class="com.spring01.Book">    <property name="name" value="历险记"></property></bean>

b) 使用有参构造进行属性注入

<bean id="book" class="com.spring01.Book">    <constructor-arg name="bname" value="时间简史"></constructor-arg></bean>

c) p名称空间注入

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"<!--在这里添加一行p--><bean id="book" class="com.spring01.Book" p:name="喜羊羊"></bean>

2.3 特殊属性(空值,特殊符号)注入

a) 空值注入

<property name="bname"><null/></property>

b) 特殊符号

<!--属性值包含特殊符号 1 把进行转义 < > 2 把带特殊符号内容写到CDATA --><property name="bname"> <value><![CDATA[<>]]></value> </property>

2.4 注入属性—外部bean

(1)创建两个类 service类和dao类
(2)在service调用dao里面的方法

public class UserService {//service类    //创建UserDao类型属性,生成set方法    private UserDao userDao;    public void setUserDao(UserDao userDao) { this.userDao = userDao;    }    public void add() { System.out.println("service add..............."); userDao.update();//调用dao方法    }}public class UserDaoImpl implements UserDao {//dao类    @Override    public void update() { System.out.println("dao update...........");    }}

(3)在spring配置文件中进行配置

<bean id="userDaoImpl" class="com.spring01.dao.UserDaoImpl"></bean><bean id="userService" class="com.spring01.service.UserService">    <property name="userDao" ref="userDaoImpl"></property></bean>

2.5 注入属性—内部bean

a) 内部bean

(1)一对多关系:部门和员工一个部门有多个员工,一个员工属于一个部门部门是一,员工是多
(2)在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示

//部门类public class Dept {    private String name;    public void setName(String name) { this.name = name;    }}//员工类public class Emp {    private String ename;    private String gender;    //员工属于某一个部门,使用对象形式表示    private Dept dept; public void setDept(Dept dept) { this.dept = dept;    }    public void setEname(String ename) { this.ename = ename;    }    public void setGender(String gender) { this.gender = gender;    }}

(3) 在spring配置文件中进行配置

<bean id="employee" class="com.spring01.bean.Employee">    <property name="name" value="lucy"></property>    <property name="gender" value=""></property>        <property name="dept"> <bean id="dept" class="com.spring01.bean.Dept">     <property name="name" value="董事会"></property> </bean>    </property></bean>

b) 级联赋值

写法一:采用外部bean

<bean id="employee" class="com.spring01.bean.Employee">    <property name="name" value="lucy"></property>    <property name="gender" value=""></property>    <property name="dept" ref="dept"></property></bean><bean id="dept" class="com.spring01.bean.Dept">    <property name="name" value="税务部"></property></bean>

写法二:需生成dept的get方法

public Dept getDept() {     return dept;}
<bean id="employee" class="com.spring01.bean.Employee">    <property name="name" value="lucy"></property>    <property name="gender" value=""></property>    <property name="dept" ref="dept"></property>    <property name="dept.name" value="技术部"></property></bean><bean id="dept" class="com.spring01.bean.Dept">    <!----></bean>

2.7 IOC 操作 Bean 管理——xml 注入集合属性

1、注入数组类型属性 2、注入 List 集合类型属性 3、注入 Map 集合类型属性

//(1)创建类,定义数组、list、map、set 类型属性,生成对应 set 方法public class Student {    private String[] courses;    private List<String> list;    private Map<String, String> map;    private Set<String> set;    //学生的课程    private List<Course> courseList;    public void setCourseList(List<Course> courseList) { this.courseList = courseList;    }    public void setCourses(String[] courses) { this.courses = courses;    }    public void setList(List<String> list) { this.list = list;    }    public void setMap(Map<String, String> map) { this.map = map;    }    public void setSet(Set<String> set) { this.set = set;    }}
<bean id="stu" class="com.spring.collectiontype.Student">        <property name="courses"> <array>     <value>Java</value>     <value>C++</value>     <value>Python</value> </array>    </property>        <property name="list"> <list>     <value>Jack</value>     <value>Linda</value> </list>    </property>        <property name="map"> <map>     <entry key="1" value="羊羊"></entry>     <entry key="2" value="聪聪"></entry> </map>    </property>        <property name="set"> <set>     <value>梨花</value>     <value>华理</value> </set></bean>

2.8 在集合里面设置对象类型值

// 课程类public class Course {    private String name;    public void setName(String name) { this.name = name;    }}
//Student类再添加以下内容//学生所学多门课程private List<Course> courseList;//创建集合public void setCourseList(List<Course> courseList) {    this.courseList = courseList;}
<bean></property>        <property name="courseList"> <list>     <ref bean="course1"></ref>     <ref bean="course2"></ref> </list>    </property></bean><bean id="course1" class="com.spring.collectiontype.Course">    <property name="name" value="Spring框架"></property></bean><bean id="course2" class="com.spring.collectiontype.Course">    <property name="name" value="SpringMVC框架"></property></bean>

以上代码表示:一个学生学习两门课程—Spring框架和SpringMVC框架

2.9 把集合注入部分提取出来

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:util="http://www.springframework.org/schema/util"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">     <util:list id="list"> <value>黄帝内经</value> <value>九阴真经</value> <value>葵花宝典</value>    </util:list>        <bean id="book" class="com.spring.collectiontype.Book"> <property name="list" ref="list"></property>    </bean></beans>

3. FactoryBean

1、Spring有两种类型bean,一种普通bean,另外一种为工厂bean(FactoryBean)
2、普通bean:在配置文件中定义bean类型就是返回类型
3、工厂bean:在配置文件定义bean类型可以和返回类型不一样
第一步 创建类,让这个类作为工厂bean,实现接口 FactoryBean
第二步 实现接口里面的方法,在实现的方法中定义返回的bean类型

public class MyBean implements FactoryBean<Course> {    //定义返回bean    @Override    public Course getObject() throws Exception { Course course = new Course(); course.setCname("Spring5教程"); return course;    }}
<bean id="myBean" class="com.spring.factorybean.MyBean"></bean>
@Test//测试public void test() {    ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");    Course course = context.getBean("myBean", Course.class);    System.out.println(course);}

这样就实现了配置文件中定义的bean类型(MyBean)和返回类型(Course)不一样

4. bean作用域

在Spring里面,默认情况下,bean是单实例对象
(1)在 spring 配置文件 bean 标签里面有属性(scope)用于设置单实例还是多实例
(2)scope 属性的值默认为singleton,表示单实例对象;prototype,表示多实例对象

<bean id="book" class="com.spring.collectiontype.Book" scope="prototype">   <property name="list" ref="list"></property></bean>
@Test    public void test() { ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml"); Book book1 = context.getBean("book", Book.class); Book book2 = context.getBean("book", Book.class); System.out.println(book1); System.out.println(book2);    }

在这里插入图片描述

book1和book2地址不同,说明创建了两个Book实例对象。

5. bean生命周期

1、生命周期 :从对象创建到对象销毁的过程
2、bean 生命周期
​ (1)通过无参构造器创建 bean 实例
​ (2)为 bean 的属性设置值和对其他 bean 引用(调用 setXxx 方法)
​ (3)调用 bean 的初始化的方法(需要进行配置初始化的方法)
​ (4)获取bean对象
​ (5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)
3、演示 bean 生命周期 :

public class Order {    private String name;    public Order() { System.out.println("1.通过无参构造创建bean实例");    }    public void setName(String name) { this.name = name; System.out.println("2.设置bean的属性值");    }    //创建执行的初始化方法    public void initMethod(){ System.out.println("3.执行初始化方法");    }    //创建销毁方法    public void destroyMethod(){ System.out.println("5.执行实例销毁方法");    }}
<bean id="order" class="com.spring.bean.Order" init-method="initMethod" destroy-method="destroyMethod">   <property name="name" value="手机"></property></bean>
@Test    public void test2() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml"); Order order = context.getBean("order", Order.class); System.out.println("4.获取到创建的bean实例对象"); System.out.println(order); //手动执行bean实例销毁方法 context.close();    }

在这里插入图片描述

6. 属性自动装配

自动装配:根据指定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入

<bean id="emp" class="com.spring.autowire.Emp" autowire="byName"><!----></bean><bean id="dept" class="com.spring.autowire.Dept">    <property name="name" value="财务部"></property></bean>

设置autowire属性,实现属性名称值的自动注入。

7. 引入外部属性配置文件

目的:配置MySQL德鲁伊连接池

方式一:直接在XML文件中配置

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>    <property name="url" value="jdbc:mysql://localhost:3306/userDB"></property>    <property name="username" value="root"></property>    <property name="password" value="root"></property></bean>

方式二:引入外部属性文件jdbc.properties进行配置 推荐
(1)创建外部属性文件,properties 格式文件,包含数据库信息(jdbc.properties)

prop.driverClass=com.mysql.jdbc.Driverprop.url=jdbc:mysql://localhost:3306/userDBprop.username=rootprop.password=root

(2)把外部 properties 属性文件引入到 spring 配置文件中 —— 引入 context 名称空间

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">     <property name="driverClassName" value="${prop.driverClass}"></property>     <property name="url" value="${prop.url}"></property>     <property name="username" value="${prop.username}"></property>     <property name="password" value="${prop.password}"></property> </bean></beans>

麦克风网