一、IOC基本原理
1.什么是IOC容器
容器:容器是一种为特定组件的运行提供必要支持的一个软件环境。例如Tomcat就是一个Servlet容器,它可以为Servlet的运行提供运行环境。类似Docker这样的软件也是一个容器,它提供了必要的Linux环境以便运行一个特定的Linux进程。通常来说,使用容器运行组件,除了提供一个组件运行环境之外,容器还提供了许多底层服务。例如,Servlet容器(如Tomcat)底层实现了TCP连接,解析HTTP协议等非常复杂的服务,如果没有容器来提供这些服务,我们就无法编写像Servlet这样代码简单,功能强大的组件。
IOC容器:Spring框架提供了IOC容器,它可以管理所有轻量级的JavaBean组件,提供的底层服务包括组件的生命周期管理,配置和组装服务,AOP支持,以及建立在AOP基础上的声明式事务服务等。后续介绍IOC容器如何对组件进行生命周期管理和配置组装服务
2.什么是IOC
- IOC(Inversion of Control),控制反转,把对象的创建和对象之间调用过程,交给Spring进行管理
- 使用IOC的目的:为了降低耦合度,借助于“第三方”实现具有依赖关系的对象之间的解耦
对象之间的依赖关系:如果我们打开机械式手表的后盖,就会看到与上面类似的情形,各个齿轮分别带动时针、分针和秒针顺时针旋转,从而在表盘上产生正确的时间。图1中描述的就是这样的一个齿轮组,它拥有多个独立的齿轮,这些齿轮相互啮合在一起,协同工作,共同完成某项任务。我们可以看到,在这样的齿轮组中,如果有一个齿轮出了问题,就可能会影响到整个齿轮组的正常运转。
IOC解耦过程:由于引进了中间位置的“第三方”,也就是IOC容器,使得A、B、C、D这4个对象没有了耦合关系,齿轮之间的传动全部依靠“第三方”了,全部对象的控制权全部上缴给“第三方”IOC容器,所以,IOC容器成了整个系统的关键核心,它起到了一种类似“粘合剂”的作用,把系统中的所有对象粘合在一起发挥作用,如果没有这个“粘合剂”,对象与对象之间会彼此失去联系,这就是有人把IOC容器比喻成“粘合剂”的由来。
去掉IOC容器后的系统:这时候,A、B、C、D这4个对象之间已经没有了耦合关系,彼此毫无联系,这样的话,当你在实现A的时候,根本无须再去考虑B、C和D了,对象之间的依赖关系已经降低到了最低程度。所以,如果真能实现IOC容器,对于系统开发而言,这将是一件多么美好的事情,参与开发的每一成员只要实现自己的类就可以了,跟别人没有任何关系!
分析:
软件系统在没有引入IOC容器之前,如图1所示,对象A依赖于对象B,那么对象A在初始化或者运行到某一点的时候,自己必须主动去创建对象B或者使用已经创建的对象B。无论是创建还是使用对象B,控制权都在自己手上。 软件系统在引入IOC容器之后,这种情形就完全改变了,如图2所示,由于IOC容器的加入,对象A与对象B之间失去了直接联系,所以,当对象A运行到需要对象B的时候,IOC容器会主动创建一个对象B注入到对象A需要的地方。对象A获得依赖对象B的过程,由主动行为变为了被动行为,控制权颠倒过来了,这就是“控制反转”这个名称的由来。
3.IOC底层原理
技术支持:
XML解析+工厂设计模式+反射机制
分析:
4.IOC的BeanFactory接口
3.1 IOC思想是基于IOC容器来完成的,IOC容器的底层就是对象工厂
3.2 Spring提供IOC容器实现的两种方式(两个接口)
(1)BeanFactory:IOC容器基本实现,是Spring内部的使用接口,不提供开发人员使用(加载配置文件时候不会创建对象,在使用对象时候才创建对象---懒汉式)
(2)ApplicationContext:BeanFactroy接口的子接口,提供更多更强大的功能,一般由开发人员进行使用(加载配置文件时候就会把在配置文件中的对象进行创建---饿汉式)
3.3 ApplicationContext接口的实现类(ClassPathXmlApplicationContext和FileSystemXmlApplicationContext)
鼠标点击要打开的接口,按F4打开树形结构
二、IOC操作---Bean管理
1.什么是Bean管理
(1)Spring创建对象
(2)Spring注入属性
2.Bean管理操作的两种方式
(1)基于XML配置文件方式实现
(2)基于注解方式实现
三、基于XML配置文件方式实现Bean管理
1.基于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">
<!--配置User对象创建-->
<bean id="user" class="com.csu.marden.User"></bean>
</beans>
2.基于XML方式注入属性(注入基本数据类型)
DI:依赖注入,就是注入属性
第一种注入方式:使用set方法进行注入
- 创建类,定义属性和对应的set方法
- 在Spring配置文件中配置对象的创建过程,并配置注入的属性,即在bean标签下使用property标签,其中name属性表示类里面属性名称,value属性表示向属性注入的值
创建实体类:
package com.csu.marden;
public class Book {
//创建属性
private String bname;
private String bauthor;
//创建属性对应的set方法
public void setBname(String bname){
this.bname=bname;
}
public void setBauthor(String bauthor){
this.bauthor=bauthor;
}
}
编写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">
<!--配置Book对象创建-->
<bean id="book" class="com.csu.marden.Book">
<!-- 使用property标签完成属性输入 -->
<!-- name属性:类里面属性名称 -->
<!-- value属性:向属性注入的值 -->
<property name="bname" value="易筋经"></property>
<property name="bauthor" value="达摩老祖"></property>
</bean>
</beans>
编写测试代码:
package com.csu.marden;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//1.加载spring配置文件
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
//2.获取配置创建的对象
Book book=context.getBean("book",Book.class);
//测试对象
System.out.println(book);
}
}
测试结果:
简化形式:p名称空间注入---------简化基于xml配置方式
- 在配置文件中添加p名称空间
- 进行属性注入,在bean标签里面进行操作(本质还是使用set方法进行属性注入)
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置Book对象创建-->
<bean id="book" class="com.csu.marden.Book" p:bname="九阳神功" p:bauthor="'无名氏">
</bean>
</beans>
第二种注入方式:使用有参构造方法注入
- 创建类,定义属性和对应的有参构造函数
- 在Spring配置文件中配置对象的创建过程,并配置注入的属性,即在bean标签下使用constructor-arg标签,其中name属性表示类里面构造器中的属性名称,value属性表示向属性注入的值
创建实体类:
package com.csu.marden;
public class Orders {
//创建属性
private String oname;
private String address;
//创建有参构造函数
public Orders(String oname, String address) {
this.oname = oname;
this.address = address;
}
@Override
public String toString() {
return "Orders [oname=" + oname + ", address=" + address + "]";
}
}
编写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 id="orders" class="com.csu.marden.Orders">
<constructor-arg name="oname" value="电脑"></constructor-arg>
<constructor-arg name="address" value="中国"></constructor-arg>
</bean>
</beans>
编写测试代码:
package com.csu.marden;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Orders orders=context.getBean("orders", Orders.class);
System.out.println(orders);
}
}
测试结果:
3. 基于XML方式注入(注入字面量属性以及对象属性)
3.1注入字面量属性
示例:向属性中添加null值
创建实体类:
package com.csu.marden;
public class Book {
//创建属性
private String bname;
private String bauthor;
private String address;
//创建属性对应的set方法
public void setBname(String bname){
this.bname=bname;
}
public void setBauthor(String bauthor){
this.bauthor=bauthor;
}
public void setAddress(String address){
this.address=address;
}
public void testDemo(){
System.out.println(bname+":"+bauthor+":"+address);
}
}
创建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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置Book对象创建-->
<bean id="book" class="com.csu.marden.Book">
<property name="bname" value="易筋经"></property>
<property name="bauthor" value="达摩老祖"></property>
<property name="address">
<null/>
</property>
</bean>
</beans>
编写测试类:
package com.csu.marden;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Book book=context.getBean("book", Book.class);
book.testDemo();
}
}
测试结果:
示例:向属性中添加带有特殊符号的值,如特殊符号:<>
创建实体类:
package com.csu.marden;
public class Book {
//创建属性
private String bname;
private String bauthor;
private String address;
//创建属性对应的set方法
public void setBname(String bname){
this.bname=bname;
}
public void setBauthor(String bauthor){
this.bauthor=bauthor;
}
public void setAddress(String address){
this.address=address;
}
public void testDemo(){
System.out.println(bname+":"+bauthor+":"+address);
}
}
创建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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置Book对象创建-->
<bean id="book" class="com.csu.marden.Book">
<property name="bname" value="易筋经"></property>
<property name="bauthor" value="达摩老祖"></property>
<!-- 属性值包含特殊符号 -->
<!-- 1.把<>进行转义 < > -->
<!-- 2.把带特殊符号内容写道CDATA中 -->
<property name="address">
<value><![CDATA[<<南京>>]]></value>
</property>
</bean>
</beans>
编写测试类:
package com.csu.marden;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Book book=context.getBean("book", Book.class);
book.testDemo();
}
}
测试结果:
外部bean和内部bean总结:
外部bean:直接在beans标签内部直接定义的bean对象,外部bean可以被多个bean对象引用(使用ref属性注入)
内部bean:在某个bean标签的内部定义的bean对象,内部bean只能被某个对象的某个属性引用(在property属性内部,定义bean对象)
3.2 注入属性---外部bean
操作:将对象类型作为属性注入,在Bean中定义属性以及set方法,随后在配置文件中使用ref将其他对象注入其中
示例:MVC模式中,service层中需要使用dao层对象,使用外部bean的方式进行创建和管理
- 创建两个类:service类和dao类
- 在service类中调用dao中的方法
- 在Spring配置文件中进行配置
创建UserDao接口和UserDaoImpl类:
package com.csu.marden.dao;
public interface UserDao {
public void update();
}
package com.csu.marden.dao;
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("dao update.........");
}
}
创建UserService类:
package com.csu.marden.service;
import com.csu.marden.dao.UserDao;
public class UserService {
//创建UserDao类型属性,生成对应的set方法
private UserDao userDao;
//生成对应的set方法
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void add(){
System.out.println("service add.........");
userDao.update();
}
}
编写Spring的xml配置文件:ref指向外部bean的id
<?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">
<!-- service和dao对象的创建 -->
<bean id="userService" class="com.csu.marden.service.UserService">
<!-- 注入userDao对象 -->
<!-- name属性:类里面属性名称 -->
<!-- ref属性:创建userDaoImpl对象时,bean标签的id值 -->
<property name="userDao" ref="userDaoImpl"></property>
</bean>
<bean id="userDaoImpl" class="com.csu.marden.dao.UserDaoImpl"></bean>
</beans>
编写测试类:
package com.csu.marden.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.service.UserService;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean2.xml");
UserService userService=context.getBean("userService", UserService.class);
userService.add();
}
}
测试结果:
3.3 注入属性---内部bean
操作:将对象类型作为属性注入,在Bean中定义属性以及set方法,随后在配置文件中的property属性中,创建内部bean
示例:部门和员工之间的一对多关系,使用内部bean的方式进行创建和管理
创建部门类:
package com.csu.marden.bean;
public class Dept {
//定义属性
private String dname;
//定义属性对应的set方法
public void setDname(String dname){
this.dname=dname;
}
@Override
public String toString() {
return "Dept [dname=" + dname + "]";
}
}
创建员工类:
package com.csu.marden.bean;
public class Emp {
private String ename;
private String gender;
//员工属于某一个部门,使用对象的形式表示
private Dept dept;
//定义属性对应的set方法
public void setEname(String ename) {
this.ename = ename;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDept(Dept dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Emp [ename=" + ename + ", gender=" + gender + ", dept=" + dept + "]";
}
}
配置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">
<!-- 内部bean -->
<bean id="emp" class="com.csu.marden.bean.Emp">
<!-- 设置两个普通属性 -->
<property name="ename" value="Lucy"></property>
<property name="gender" value="女"></property>
<!-- 设置对象类型属性,使用内部bean -->
<property name="dept">
<bean id="dept" class="com.csu.marden.bean.Dept">
<property name="dname" value="安保部"></property>
</bean>
</property>
</bean>
</beans>
编写测试类:
package com.csu.marden.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.bean.Emp;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean2.xml");
Emp emp=context.getBean("emp", Emp.class);
System.out.println(emp);
}
}
测试结果:
3.4 注入属性---级联赋值
第一种写法:创建两个bean,在被引用的bean中独立赋值
<?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 -->
<bean id="emp" class="com.csu.marden.bean.Emp">
<!-- 设置两个普通属性 -->
<property name="ename" value="Lucy"></property>
<property name="gender" value="女"></property>
<property name="dept" ref="dept"></property>
</bean>
<bean id="dept" class="com.csu.marden.bean.Dept">
<property name="dname" value="销售部"></property>
</bean>
</beans>
第二种写法:创建两个bean,在引用bean中赋值
此例中,emp对象中有属性dept,而dept是对象类型的,要想向emp的属性:dept赋值,必须拿到dept对象,因此必须有dept的get方法
<?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 id="emp" class="com.csu.marden.bean.Emp">
<!-- 设置两个普通属性 -->
<property name="ename" value="lucy"></property>
<property name="gender" value="女"></property>
<!-- 级联赋值 -->
<!-- 使用property的ref属性,建立bean之间的引用关系 -->
<property name="dept" ref="dept"></property>
<!-- 为级联属性赋值,首先必须引用级联属性的类 -->
<property name="dept.dname" value="技术部">
</property>
</bean>
<bean id="dept" class="com.csu.marden.bean.Dept">
<!-- <property name="dname" value="财务部"></property> -->
</bean>
</beans>
3.4 基于XML方式注入属性(注入集合属性)
- 注入数组类型属性
- 注入List集合类型属性
- 注入Set集合类型属性
- 注入Map集合类型属性
创建Student类,定义数组,list,set,map类型属性,生成对应的se方法:
package com.csu.marden.collectionType;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Student {
//数组类型属性
private String [] courses;
//List集合类型属性
private List<String> list;
//Set集合类型属性
private Set<String> set;
//Map集合类型属性
private Map<String,String> map;
public void setCourses(String[] courses) {
this.courses = courses;
}
public void setList(List<String> list) {
this.list = list;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void test(){
System.out.println(Arrays.toString(courses));
System.out.println(list);
System.out.println(set);
System.out.println(map);
}
}
在Spring的配置文件中进行配置:
<?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 id="student" class="com.csu.marden.collectionType.Student">
<!-- 集合类型属性注入 -->
<property name="courses">
<array>
<value>Java课程</value>
<value>数据库课程</value>
<value>数据结构课程</value>
</array>
</property>
<!-- list类型属性注入 -->
<property name="list">
<list>
<value>张三</value>
<value>小三</value>
</list>
</property>
<!-- set类型属性注入 -->
<property name="set">
<set>
<value>MySQL</value>
<value>Redis</value>
</set>
</property>
<!-- map类型属性注入 -->
<property name="map">
<map>
<entry key="JAVA" value="java"></entry>
<entry key="PHP" value="php"></entry>
<entry key="PYTHON" value="python"></entry>
</map>
</property>
</bean>
</beans>
编写测试类:
package com.csu.marden.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.collectionType.Student;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Student student=context.getBean("student", Student.class);
student.test();
}
}
测试结果:
问题一:在集合里面设置对象类型值
示例:学生类中包含课程属性,课程属性是一个对象,将课程对象注入到student对象中
创建课程类:
package com.csu.marden.collectionType;
public class Course {
private String cname;
public void setCname(String cname) {
this.cname = cname;
}
@Override
public String toString() {
return "Course [cname=" + cname + "]";
}
}
创建学生类:
package com.csu.marden.collectionType;
import java.util.List;
public class Student {
//学生所学的多门课程
private List<Course> courseList;
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
public void test(){
System.out.println(courseList);
}
}
编写Spring配置文件:
<?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">
<!-- 创建student对象 -->
<bean id="student" class="com.csu.marden.collectionType.Student">
<!-- 注入list集合类型,但注入的值是对象类型 -->
<property name="courseList">
<list>
<ref bean="course1"></ref>
<ref bean="course2"></ref>
</list>
</property>
</bean>
<!-- 创建第一个course对象 -->
<bean id="course1" class="com.csu.marden.collectionType.Course">
<property name="cname" value="Spring5框架课程'"></property>
</bean>
<!-- 创建第二个course对象 -->
<bean id="course2" class="com.csu.marden.collectionType.Course">
<property name="cname" value="MyBatis框架课程'"></property>
</bean>
</beans>
编写测试类:
package com.csu.marden.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.collectionType.Student;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Student student=context.getBean("student", Student.class);
student.test();
}
}
测试结果:
注意:向集合中注入属性值,注入基本数据类型使用value属性,注入对象类型使用ref属性进行引用
问题二:将集合注入部分抽取出来
在Spring框架的配置文件中,引入名称空间util:
使用util标签完成list集合注入提取:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 提取list集合类型的属性注入 -->
<util:list id="bookList">
<value>易筋经</value>
<value>九阴真经</value>
<value>九阳神功</value>
</util:list>
<!-- 提取list集合类型的属性注入使用 -->
<bean id="book" class="com.csu.marden.collectionType.Book">
<property name="list" ref="bookList"></property>
</bean>
</beans>
编写测试类:
package com.csu.marden.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.collectionType.Book;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean2.xml");
Book book=context.getBean("book", Book.class);
System.out.println(book);
}
}
测试结果:
注意:集合list,set,map均可以抽取分离出来,需要时,使用ref属性引入
4.IOC操作(Bean管理-----FactoryBean)
本质:当一个Bean实现了FactoryBean接口后,Spring会先实例化这个工厂,然后调用getObject()创建真正的Bean。getObjectType()可以指定创建的Bean的类型,因为指定类型不一定与实际类型一致,可以是接口或抽象类。因此要注意,如果定义了一个FactoryBean,Spring创建的Bean实际上是这个FactoryBean的getObject()方法返回的Bean。
说明:
- Spring框架有两种类型的bean,一种是普通bean,另一种是工厂bean(FactoryBean)
- 普通bean:在配置文件中定义bean类型就是返回类型。
- 工厂bean:在配置文件中定义bean类型可以和返回类型不一样。
通过FactroyBean创建bean:
第一步 创建类,让这个类作为工厂bean,实现接口FactoryBean
第二步 实现接口里面的方法,在实现的方法中定义返回的bean类型
第三步 配置Spring中的配置文件
第四步 测试案例
package com.csu.marden.factoryBean;
public class Course {
private String cname;
public void setCname(String cname) {
this.cname = cname;
}
@Override
public String toString() {
return "Course [cname=" + cname + "]";
}
}
package com.csu.marden.factoryBean;
import org.springframework.beans.factory.FactoryBean;
public class MyBean implements FactoryBean<Course>{
@Override
public Course getObject() throws Exception {
Course course = new Course();
course.setCname("Java课程设计");
return course;
}
@Override
public Class<?> getObjectType() {
// TODO Auto-generated method stub
return null;
}
}
<?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 id="myBean" class="com.csu.marden.factoryBean.MyBean"></bean>
</beans>
package com.csu.marden.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.factoryBean.Course;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Course course=context.getBean("myBean", Course.class);
System.out.println(course);
}
}
5.IOC操作(Bean管理-----Bean的作用域)
- 在Spring里,默认情况下,bean是单实例对象
- 在Spring里,通过bean标签的scope属性可以设置单实例还是多实例(singleton表示单实例对象,默认值;prototype表示多实例对象)
- 设置scope的值是singleton,或者默认不设置情况下,加载Spring配置文件的时候就会创建单实例对象(加载时就创建,最后调用getBean方法获取到的Bean总是同一个实例对象)
- 设置scope的值是prototype,并不是在加载Spring配置文件时候创建对象,而是在调用getBean方法的时候创建多实例对象(每次调用getBean方法才创建,得到的都是新的实例对象)
实例:测试scope属性设置单实例对象与多实例对象
package com.csu.marden.factoryBean;
public class Course {
private String cname;
public void setCname(String cname) {
this.cname = cname;
}
}
package com.csu.marden.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.factoryBean.Course;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Course course1=context.getBean("course", Course.class);
Course course2=context.getBean("course", Course.class);
System.out.println(course1);
System.out.println(course2);
}
}
6.IOC操作(Bean管理-----Bean的生命周期)
生命周期:从对象的创建到对象的销毁的过程
Bean生命周期:
- 通过构造器创建Bean实例(无参数构造)
- 为Bean的属性设置值和对其他Bean的引用(调用set方法)
- 调用Bean的初始化方法(需要进行配置初始化的方法)
- Bean可以使用了(对象获取到了)
- 当容器关闭时,调用Bean的销毁方法(需要进行配置销毁的方法)
示例:演示Bean的生命周期
package com.csu.marden.bean;
public class Orders {
private String oname;
public void setOname(String oname){
this.oname=oname;
System.out.println("第二步:调用set方法设置属性值");
}
public Orders(){
System.out.println("第一步:执行无参数构造创建Bean实例");
}
//创建执行的初始化的方法
public void initMethod(){
System.out.println("第三步:执行初始化的方法");
}
//创建执行的销毁的方法
public void destroyMethod(){
System.out.println("第五步:执行销毁的方法");
}
}
package com.csu.marden.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Orders orders=context.getBean("orders", Orders.class);
System.out.println("第四步:获取创建Bean实例对象");
System.out.println(orders);
//手动让Bean实例销毁
context.close();
}
}
<?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 id="orders" class="com.csu.marden.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
<property name="oname" value="手机"></property>
</bean>
</beans>
测试结果:
Bean的后置处理器,Bean生命周期有七步:
- 通过构造器创建Bean实例(无参数构造)
- 为Bean的属性设置值和对其他Bean的引用(调用set方法)
- 把Bean实例传递给Bean后置处理器的方法:postProcessBeforeInitialization
- 调用Bean的初始化方法(需要进行配置初始化的方法)
- 把Bean实例传递给Bean后置处理器的方法:postProcessAfterInitialization
- Bean可以使用了(对象获取到了)
- 当容器关闭时,调用Bean的销毁方法(需要进行配置销毁的方法)
示例:演示添加后置处理器效果
创建类,实现BeanPostProcessor接口,创建后置处理器:
package com.csu.marden.bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBean implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之前执行的方法");
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之后执行的方法");
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
package com.csu.marden.bean;
public class Orders {
private String oname;
public void setOname(String oname){
this.oname=oname;
System.out.println("第二步:调用set方法设置属性值");
}
public Orders(){
System.out.println("第一步:执行无参数构造创建Bean实例");
}
//创建执行的初始化的方法
public void initMethod(){
System.out.println("第三步:执行初始化的方法");
}
//创建执行的销毁的方法
public void destroyMethod(){
System.out.println("第五步:执行销毁的方法");
}
}
package com.csu.marden.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
Orders orders=context.getBean("orders", Orders.class);
System.out.println("第四步:获取创建Bean实例对象");
System.out.println(orders);
//手动让Bean实例销毁
context.close();
}
}
<?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 id="orders" class="com.csu.marden.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
<property name="oname" value="手机"></property>
</bean>
<!-- 配置后置处理器 -->
<bean id="myBean" class="com.csu.marden.bean.MyBean"></bean>
</beans>
测试结果:
7.IOC操作(Bean管理-----XML自动装配)
自动装配:根据指定的装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入
- 在bean标签中,使用autowire配置自动装配,其中autowire属性有两个常用的值,分别是byName和byType
-
byName根据属性名称注入,注入值bean的id值和属性名称保持一致
-
byType根据属性类型注入,若存在多个相同类型,则无法使用
IOC操作(Bean管理-----外部属性文件)
场景:连接数据库时候,需要配置数据库的地址,用户名,密码。这些信息可以直接写死,也可以放在外部文件。
方式一:直接配置数据库信息
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 直接配置连接池 -->
<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/csu_duty"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
方式二:引入外部属性文件配置数据库连接池
创建外部属性文件,properties格式文件,写数据库相关信息
把外部properties属性文件引入到Spring配置文件中-----引入context名称空间
<?xml version="1.0" encoding="UTF-8"?>
<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.driver}"></property>
<property name="url" value="${prop.url}"></property>
<property name="username" value="${prop.username}"></property>
<property name="password" value="${prop.password}"></property>
</bean>
</beans>
四、基于注解方式实现Bean管理
- 注解:代码中的特殊标记,格式:@注解名称(属性名称1=属性值1,属性名称2=属性值2......)
- 使用注解,注解可以作用域类上面,方法上面,属性上面
- 使用注解的目的:简化XML的配置
1.Bean管理(创建对象)
- @Component
- @Service
- @Controller
- @Repository
注意:上面四个注解功能是一样的,都可以用来创建Bean实例
基于注解方式实现对象创建:
第一步:引入依赖
第二步:开启组件扫描
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 开启组件扫描
1.如果扫描多个包,多个包使用逗号隔开
2.如果扫描多个包,扫描包的上层目录
-->
<context:component-scan base-package="com.csu.marden"></context:component-scan>
</beans>
第三步:创建类,在类上面添加添加创建对象的注解
package com.csu.marden;
import org.springframework.stereotype.Component;
//在注解里面value属性值可以省略不写,默认是类的名称,首字母小写
//该注解相当于:<bean id="" class=""></bean>
@Component(value="userService")
public class UserService {
public void add(){
System.out.println("service add.........");
}
}
第四步:编写测试类
package com.csu.marden;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
UserService userService=context.getBean("userService",UserService.class);
System.out.println(userService);
userService.add();
}
}
注意:开启组件扫描的配置细节(能看懂)
- 在组件扫描配置中,将use-default-filters属性设置为true,或默认不进行配置,则扫描全部组件
- 在组件扫描配置中,将use-default-filters属性设置为false,表示不进行全部组件的扫描,此时需要自己配置扫描哪些内容
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 开启组件扫描
1.如果扫描多个包,多个包使用逗号隔开
2.如果扫描多个包,扫描包的上层目录
-->
<context:component-scan base-package="com.csu.marden"></context:component-scan>
<!-- 实例1
use-default-filters="false" 表示现在不使用默认的filter,而使用自己配置的filter
context:include-filter 设置扫描哪些内容
下述配置表明扫描com.csu.marden包中的内容时,不适用默认的filter,而使用自定义的filter,并且只扫描@Controller注解
-->
<context:component-scan base-package="com.csu.marden" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 实例2
context:exclude-filter 设置哪些内容不进行扫描
下述配置表明扫描com.csu.marden包中的内容时,不扫描@Controller注解
-->
<context:component-scan base-package="com.csu.marden">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
2.Bean管理(注入属性)
第一种:@Autowired(根据属性类型进行自动注入/装配)
示例:在包中有dao和service两个包,要想在service中使用dao
第一步:创建service和dao对象,在service和dao类上添加创建对象注解
package com.csu.marden.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao{
@Override
public void add() {
System.out.println("dao add.........");
}
}
package com.csu.marden.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.csu.marden.dao.UserDao;
@Service
public class UserService {
//定义dao类型属性
//不需要添加set方法
@Autowired //根据类型进行注入
private UserDao userDao;
public void add(){
System.out.println("service add.........");
userDao.add();
}
}
第二步:在service中注入dao对象,在service类添加dao类型属性,在属性上面使用注解
package com.csu.marden.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.csu.marden.dao.UserDao;
@Service
public class UserService {
//定义dao类型属性
//不需要添加set方法
@Autowired //根据类型进行注入
private UserDao userDao;
public void add(){
System.out.println("service add.........");
userDao.add();
}
}
第三步:测试效果
package com.csu.marden;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.service.UserService;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
UserService userService=context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
}
第二种:@Qualifier(根据属性名称进行注入)
注意:@Qualifier和@Autowired一起使用。使用场景,例如接口有多个实现类,根据类型无法指定注入那个类对象,此时根据对象名称进行属性注入
对UserDaoImpl对象创建时,使用注解指定名称
在UserService中使用@Qualifier注解进行注入时,与@Autowired注解一起使用
第三种:@Resource(可以根据属性类型注入,也可以根据属性名称注入)
第四种:@Value(注入普通类型属性)
注意:使用@Value注解可以注入基本数据类型
package com.csu.marden.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Value(value="abc")
private String name;
@Value(value="12")
private int age;
public void show(){
System.out.println(name+":"+age);
}
}
package com.csu.marden;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.csu.marden.service.UserService;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
UserService userService=context.getBean("userService", UserService.class);
System.out.println(userService);
userService.show();
}
}
3.Bean管理(完全注解开发)---------------不适用配置文件,只是用注解
第一步:创建配置类,替代XML配置文件
package com.csu.marden.conf;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages={"com.csu.marden"})
public class SpringConfig {
}
第二步:编写测试类
package com.csu.marden;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.csu.marden.conf.SpringConfig;
import com.csu.marden.service.UserService;
public class Test {
public static void main(String[] args) {
//加载配置类
ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
UserService uservice=context.getBean("userService", UserService.class);
System.out.println(uservice);
uservice.show();
}
}