1. IOC底层原理
1.1 什么是IOC
(1)控制反转,把对象创建和对象之间的调用过程,交给Spring管理
(2)使用IOC目的:为了降低耦合度
(3)做入门案例就是IOC实现
1.2 IOC底层管理
(1)xml解析,工厂模式,反射。
2. IOC接口(BeanFactory)
- IOC思想基于IOC容器完成,IOC容器底层就是对象工厂
- Spring提供IOC实现两种方式:(两个接口)
(1)BeanFactory: IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用。
此接口在加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象。
(2)ApplicationContext:BeanFactory接口的子接口,提供更多更强大的功能,一般由开发人员进行使用。
加载配置文件时候就会把在配置文件对象进行创建。 - ApplicationContext接口有实现类
什么是Bean管理?
Bean管理指的是两个操作,(1)Spring创建对象,(2)Spring注入属性
3. IOC操作Bean管理(基于xml配置文件)
3.1 基于xml方式创建对象
<!--配置User对象的创建-->
<bean id="user" class="com.example.spring5.User"></bean>
(1)在Spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象的创建
(2) 在bean标签中有很多属性,介绍常用的属性
- id属性:唯一标识
- class属性:类全路径(包含类路径)
(3) 创建对象时候,默认也是执行无参的构造方法完成对象的创建
3.2 基于xml方式注入属性
(1) DI:依赖注入,就是注入属性
第一种注入方式:使用set方法进行注入
第一步: 创建类,定义属性和对应的set方法
public class Book {
private String bName;
private String bAuthor;
public void setbName(String bName) {
this.bName = bName;
}
public void setbAuthor(String bAuthor) {
this.bAuthor = bAuthor;
}
}
第二步: 在Spring配置文件配置对象的创建,配置属性注入。
<bean id="book" class="com.example.spring5.Book">
<!--使用Property完成属性注入
name:类里面属性名称
value:向属性注入的值
-->
<property name="bName" value="易筋经"></property>
<property name="bAuthor" value="达摩老祖"></property>
</bean>
//1. 加载Spring的配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//2. 获取对象
Book book = context.getBean("book", Book.class);
第二种注入方式:使用有参构造注入
第一步:创建类,定义属性,创建属性对应的有参构造方法
public class Orders {
private String oname;
private String address;
public Orders(String oname, String address) {
this.oname = oname;
this.address = address;
}
}
第二步:在Spring配置文件中进行配置
<!--有参构造注入属性-->
<bean id="orders" class="com.example.spring5.Orders" >
<constructor-arg name="oname" value="电脑"></constructor-arg>
<constructor-arg name="address" value="China"></constructor-arg>
</bean>
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
Orders orders = context.getBean("orders", Orders.class);
第三种注入方式:p名称空间注入(了解)
(1)使用p名称空间注入,基于xml注入方式的简化
第一步:添加p名称空间在配置文件中
第二步:进行属性注入,在bean标签里面进行操作。
<bean id="book" class="com.example.spring5.Book" p:bName="九阳神功" p:bAuthor="无名氏"></bean>
xml注入其他类型属性
- 字面量
(1)null值
<!--null值-->
<property name="address">
<null/>
</property>
(2) 属性值包含特殊符号
<!--属性值中包含特殊符号
1. 把<>进行转义 < (表示<) 或 > (表示>)
2. 把带特殊符号内容写到CDATA中
-->
<property name="address">
<value>
<![CDATA[<<南京>>]]>
</value>
</property>
</bean>
- 注入属性–外部bean
(1)创建两个类service类和dao类
(2)在service类调用dao里面的方法
(3)在spring的配置文件中进行配置
public class UserService {
//创建UserDao类型的属性,生成set方法
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void add() {
System.out.println("service add");
userDao.update();
}
}
public interface UserDao {
public void update();
}
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("dao update");
}
}
<!--1. service和dao对象创建-->
<bean id="userService" class="com.example.spring5.services.UserService">
<!--注入userDao对象
name属性:类里面属性名称
ref属性:创建userDao对象bean标签id值
-->
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.example.spring5.dao.UserDaoImpl"></bean>
测试
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
结果
service add
dao update
- 注入属性–内部bean
(1)一对多关系:部门和员工。一个部门有多个员工,一个员工属于一个部门
(2)在实体类之间标识一对多的关系
public class Department {
private String dName;
public void setdName(String dName) {
this.dName = dName;
}
}
public class Employee {
private String eName;
private String gender;
private Department department;
public void setDepartment(Department department) {
this.department = department;
}
public void seteName(String eName) {
this.eName = eName;
}
public void setGender(String gender) {
this.gender = gender;
}
}
(3)在spring的配置文件中进行配置
<!--内部bean-->
<bean id="employee" class="com.example.spring5.bean.Employee">
<!--普通属性-->
<property name="eName" value="lucy"></property>
<property name="gender" value="女"></property>
<!--对象类型属性-->
<property name="department">
<bean id="department" class="com.example.spring5.bean.Department">
<property name="dName" value="安保部"></property>
</bean>
</property>
</bean>
- 注入属性–级联赋值
(1)第一种写法
<!--级联赋值-->
<bean id="employee" class="com.example.spring5.bean.Employee">
<!--普通属性-->
<property name="eName" value="lucy"></property>
<property name="gender" value="女"></property>
<!--级联赋值-->
<property name="department" ref="department"></property>
</bean>
<bean id="department" class="com.example.spring5.bean.Department">
<property name="dName" value="安保部"></property>
</bean>
(2) 第二种写法
<!--级联赋值-->
<bean id="employee" class="com.example.spring5.bean.Employee">
<!--普通属性-->
<property name="eName" value="lucy"></property>
<property name="gender" value="女"></property>
<!--级联赋值-->
<property name="department" ref="department"></property>
<property name="department.dName" value="技术部"></property>
</bean>
<bean id="department" class="com.example.spring5.bean.Department">
</bean>
- 注入集合属性
- 注入数组类型属性
- 注入List集合类型属性
- 注入Map集合类型属性
- 注入Set集合类型属性
第一步:创建类,定义数组、list、map、set类型属性
public class Student {
private String[] course;
private List<String> list;
private Map<String, String> maps;
private Set<String> sets;
public void setSets(Set<String> sets) {
this.sets = sets;
}
public void setCourse(String[] course) {
this.course = course;
}
public void setList(List<String> list) {
this.list = list;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public void testMethode() {
System.out.println(Arrays.toString(course));
System.out.println(list);
System.out.println(maps);
System.out.println(sets);
}
}
第二步:在Spring配置文件中进行配置
<!--集合类型属性注入-->
<bean id="student" class="org.example.spring5.collectiontype.Student">
<property name="course">
<array>
<value>java</value>
<value>mysql</value>
</array>
</property>
<property name="list">
<list>
<value>a</value>
<value>b</value>
<value>c</value>
</list>
</property>
<property name="maps">
<map>
<entry key="JAVA" value="java"></entry>
<entry key="PHP" value="php"></entry>
</map>
</property>
<property name="sets">
<set>
<value>aa</value>
<value>bb</value>
<value>cc</value>
</set>
</property>
</bean>
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
Student student = context.getBean("student", Student.class);
- 在集合里面设置对象类型值
public class Student {
private List<Course> courseList;
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
}
public class Course {
String cName;
public void setcName(String cName) {
this.cName = cName;
}
}
<bean id="student" class="org.example.spring5.collectiontype.Student">
<!--注入list集合类型-,值是对象类型-->
<property name="courseList">
<list>
<ref bean="course1"></ref>
<ref bean="course2"></ref>
</list>
</property>
</bean>
<bean id="course1" class="org.example.spring5.collectiontype.Course">
<property name="cName" value="Spring5框架"></property>
</bean>
<bean id="course2" class="org.example.spring5.collectiontype.Course">
<property name="cName" value="Mybatis框架"></property>
</bean>
- 把集合注入部分提取出来
第一步:在Spring配置文件中引入名称空间util
public class Book {
private List<String> list;
public void setList(List<String> list) {
this.list = 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: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">
<!--添加 xmlns:util-->
<!--提取list集合属性注入-->
<util:list id="bookList">
<value>易筋经</value>
<value>九阴真经</value>
<value>九阳神功</value>
</util:list>
<!--提取list集合类型属性注入使用-->
<bean id="book" class="org.example.spring5.collectiontype.Book">
<property name="list" ref="bookList"></property>
</bean>
</beans>
IOC操作bean管理(FactoryBean)
- Spring有两种类型的bean,一种是普通bean,另一种是工厂bean(FactoryBean)
- 普通bean:在配置文件中定义bean的类型就是返回类型
- 工厂bean:在配置文件中定义bean的类型可以和返回类型不一样。
第一步:创建类,让这个类作为工厂bean,实现FactoryBean
第二步:实现接口里面的方法,在实现的方法中定义返回的bean类型。
public class MyBean implements FactoryBean<Course> {
//定义返回bean
@Override
public Course getObject() throws Exception {
Course course = new Course();
course.setcName("abc");
return course;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
public class Course {
String cName;
public void setcName(String cName) {
this.cName = cName;
}
}
<bean id="mybean" class="org.example.spring5.factorybean.MyBean">
ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
Course course = context.getBean("mybean", Course.class);
5. bean的作用域
- 在Spring里面,设置创建的bean实例是单实例还是多实例
- 在Spring里面,默认情况下,创建的bean是单实例对象
//证明默认是单实例对象
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
Student student1 = context.getBean("student", Student.class);
Student student2 = context.getBean("student", Student.class);
System.out.println(student1);
System.out.println(student2);
org.example.spring5.collectiontype.Student@2eda0940
org.example.spring5.collectiontype.Student@2eda0940
- 如何设置单实例还是多实例
(1) 在Spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例
(2) scope属性值
第一个值 默认值,singleton,表示是单实例对象
第二个值 prototype,表示是多实例对象
<bean id="book" class="org.example.spring5.collectiontype.Book" scope="prototype"></bean>
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
Book book1 = context.getBean("book", Book.class);
Book book2 = context.getBean("book", Book.class);
System.out.println(book1 == book2);//false
(3)singleton和prototype区别
第一 singleton单实例,propotype多实例
第二 设置scope的值是singleton的时候,加载spring配置文件时候就会创建单实例对象
设置scope的值是propotype的时候,不是在加载spring配置文件时候创建对象,在调用getBean方法时后创建多实例对象
6. Bean的生命周期
- 生命周期
(1)从对象的创建到对象的销毁的过程 - bean的生命周期
(1)通过构造器创建bean实例(无参构造器)
(2)为bean的属性设置值和其他bean的引用(调用set方法)
(3)调用bean的初始化的方法(需要进行配置)
(4)bean可以使用了(对象获取到了)
(5)当容器关闭时候,调用bean的销毁的方法(需要进行配置销毁方法) - 演示bean的生命周期
<bean id="orders" class="org.example.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
<property name="oName" value="手机"></property>
</bean>
private String oName;
public Orders() {
System.out.println("第一步执行无参构造器创建bean实例");
}
public void setoName(String oName) {
this.oName = oName;
System.out.println("第二步执行调用set方法设置属性值");
}
//创建执行的初始化方法
public void initMethod() {
System.out.println("第三步执行初始化方法");
}
//创建执行的销毁方法
public void destroyMethod() {
System.out.println("第五步执行销毁方法");
}
}
@Test
public void test3() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
Orders orders = context.getBean("orders", Orders.class);
System.out.println("第四步 获取创建bean实例对象");
//手动让bean实例销毁
context.close();
}
-
加入bean的后置处理器,bean生命周期有7步
(1)通过构造器创建bean实例(无参构造器)
(2)为bean的属性设置值和其他bean的引用(调用set方法)
(3)把bean实例传递bean后置处理器的方法postProcessBeforeInitialization()
(4)调用bean的初始化的方法(需要进行配置)
(5)把bean实例传递bean后置处理器的方法postProcessAfterInitialization()
(6)bean可以使用了(对象获取到了)
(7)当容器关闭时候,调用bean的销毁的方法(需要进行配置销毁方法) -
演示添加后置处理器的效果
(1) 创建类,实现接口BeanPostProcessor ,创建后置处理器
public class MyBeanPost implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之前执行的方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之后执行的方法");
return bean;
}
}
(2)配置后置处理器
<bean id="myBeanPost" class="org.example.spring5.bean.MyBeanPost"></bean>
7. xml自动装配
- 什么是自动装配?
(1) 根据指定装配规则(属性名称或属性类型),Spring自动将匹配的属性值进行注入 - 演示自动装配的过程
(1)根据属性的名称自动注入byName
(2)根据属性的类型自动注入byType
public class Employee {
private Department department;
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Employee{" +
"department=" + department +
'}';
}
}
public class Department {
@Override
public String toString() {
return "Department{}";
}
}
<!--实现自动装配
bean标签属性autowire, 配置自动装配
autowire属性常用两个值:byName根据属性名称注入 byType根据属性的类型注入-->
<bean id="employee" class="org.example.spring5.autowire.Employee" autowire="byName">
</bean>
<bean id="department" class="org.example.spring5.autowire.Department"></bean>
@Test
public void test4() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
Employee employee = context.getBean("employee", Employee.class);
System.out.println(employee);//Employee{department=Department{}}
}
8. 引入外部属性文件
- 直接配置数据库信息
(1)配置德鲁伊连接池
(2)引入德鲁伊连接池依赖的jar包
<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>
- 通过引入外部属性文件配置数据库连接池
(1) 创建外部属性文件,properties格式文件,写数据库信息
(2)把外部的properties属性文件引入到Spring的配置文件中
- 引入context名称空间
- 在spring配置文件中使用标签引入外部属性文件
<!--引入外部属性文件-->
<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>
9. IOC操作Bean管理(基于注解)
- 什么是注解?
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值…)
(2)使用注解,注解作用在类的上面,方法上面,属性上面。
(3)使用注解目的:简化xml配置 - Spring针对bean管理中创建对象提供注解
(1)@Component
(2)@Service
(3)@Controller
(4)@Repository
上面的四个注解功能是一样的,都可以用来创建bean实例。 - 基于注解方式实现对象的创建
第一步:引入依赖apring-aop.jar
第二步:开启组件扫描
<?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. 如果扫描多个包,多个包使用逗号隔开或扫描包上层目录-->
<context:component-scan base-package="org.example.spring5"></context:component-scan>
</beans>
第三步:创建类,在类上面添加创建对象的注解
//注解里面的value属性值可以不写
//默认值是类的名称,首字母小写如 UserService 默认userService
//@Service
//@Controller
//@Repository
@Component(value="userService") //<bean id="userService" class=""></bean>
public class UserService {
public void add() {
System.out.println("service add...");
}
}
测试
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
- 开启组件扫描细节配置
看懂如下配置
<!--示例1
use-default-filters="false" 表示现在不使用默认filter,自己配置filter
context:include-filter,设置扫描那些内容-->
<context:component-scan base-package="org.example.spring5" use-default-filters="false">
<!--只扫描带Controller注解的类-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--示例2
下面配置扫描包所有内容
context:exclude-filter:设置哪些内容步进行扫描-->
<context:component-scan base-package="org.example.spring5">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
- 基于注解方式实现属性的注入
(1) @AutoWired:根据属性类型进行自动装配
第一步:把Service和dao对象创建,在service和dao类添加创建对象注解
第二步:在service中注入dao对象,在service类添加dao类型属性,在属性上面使用注解
public class UserService {
//定义dao类型属性
//不需要添加set方法(已经封装好了)
//添加注入属性注解
@Autowired
private UserDao dao;
public void add() {
System.out.println("service add...");
dao.add();
}
}
public interface UserDao {
void add();
}
@Repository
public class UserDaoImpl implements UserDao{
@Override
public void add() {
System.out.println("dao add...");
}
}
(2) @Qualifier:根据属性名称进行注入
这个@qualifier注解需要和@Autowired一起使用,不能单独使用
在UserDao有多个实现类时,可以使用@qualifier指定具体的实现类
@Qualifier(value = "userDaoImpl")//根据名称进行注入
(3) @Resource:可以根据类型注入,也可以根据名称注入
@Resource//根据类型进行注入
@Resource(name="userDaoImpl")//根据名称进行注入
注意:@Resource在javax.annotation包中,不是在org.springframework.beans.factory.annotation包中,Spring建议使用@Autowired或@Qualifier
(4)@Value:注入普通类型属性
@Value(value = "abc")
private String name;
- 完全注解开发
(1)创建配置类,代替xml配置文件
@Configuration //作为配置类,代替xml配置文件
@ComponentScan(basePackages = {"org.example.spring5"})
public class SpringConfig {
}
(2)编写测试类
@Test
public void test2() {
//加载配置类
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}