旅游网站建设分析,kol合作推广,网站备案专员,html5博客网站源码一、Spring 简介
1.简介 文档下载地址#xff1a;Index of /spring-framework/docs
1.简介 Spring framework 是 Spring 基础框架 学习Spring 家族产品 Spring framework SpringBoot SpringCloud Spring 能用来做什么 开发 WEB 项目 微服务 分布式系统 Spring framew…一、Spring 简介
1.简介 文档下载地址Index of /spring-framework/docs
1.简介 Spring framework 是 Spring 基础框架 学习Spring 家族产品 Spring framework SpringBoot SpringCloud Spring 能用来做什么 开发 WEB 项目 微服务 分布式系统 Spring framework 是 Spring 最基础的框架是其它框架技术的基础 SpringBoot 是用来做简化开发的单一项目 SpringCloud 做分布式微服务相关的拆分大单体项目为小模块项目
2.Spring 概述
2.1 Spring framework 介绍 概述spring 提供了基础框架你不必关心框架细节只需要专注于代码业务逻辑 优点 组件化模块化的通过很多模块与组件组合成 spring 应用以后可以通过 Xml 或者注解的方式去操作 控制反转 Inversion of Control (IoC) 传统创建对象都是通过认为的new 对象的方式把控制创建对象的权利转交给Spring 依赖注入Dependency Injection自动化的注入属性
3.模块
3.1 Spring 系统架构图 3.2模块介绍 Core Container核心容器是Spring 最核心的模块以后用到的都依赖该模块实现 Aop面向切面编程目的是不改变原有代码的前提下对功能进行增强 Aspects是Aop 具体实现 Data Access/Integration数据层 Data Access数据访问的 Data Integration数据集成 Transactios支持事务操作通过 AOP 来实现释放我们的双手 WebWEB 层SpringMVC 框架的 Servlet Web Test做集成测试 整合 Junit 做单元测试
二、IOC
1.概述 IOCInversion of Control 控制反转可以让容器负责对象的创建以及销毁操作对象在容器中叫 bean
2.回顾问题
2.1问题写了太多与业务无关的代码 耦合度非常高写了很多和业务无关的代码 不利于项目的升级迭代 思考的解决方案 能够直接获取 mapper 接口而不必去关心底层的获取方式 3.bean 配置
3.1.创建 spring01 项目
项目结构 添加 Spring 依赖
dependencies
!-- 添加 spring 依赖--dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.2.17.RELEASE/version/dependency
!-- 添加 junit 依赖--dependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.12/version
!-- scopetest/scope--/dependency/dependencies
3.2添加 Student 类
创建空学生类
3.3添加 Spring 配置文件 开始配置 javabean
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
!-- 配置 Student 学生类--bean idstudent namestu classcn.sycoder.domian.Student/bean
/beans 3.4属性介绍
属性名称说明id给 bean 起名字定义id 不能重复name给 bean 起别名class类全限定类名
4.容器创建
4.1ClassPathXmlApplicationContext
ApplicationContext context new ClassPathXmlApplicationContext(beans.xml);
System.out.println(context);
4.2.FileSystemXmlApplicationContext
ApplicationContext ctx new FileSystemXmlApplicationContext(绝对路径地址); 使用 ClassPathXmlApplicationContext 获取方式会出现如下问题 5.从容器中获取 bean
5.1根据id 获取
ApplicationContext context new ClassPathXmlApplicationContext(beans.xml);//从容器中根据 id 获取 bean 对象
Student stu (Student)context.getBean(student);//通过别名获取 bean 对象
Student stuByName (Student)context.getBean(stu); 注意如果id重复会有如下问题
5.2根据id和类型
ApplicationContext context new ClassPathXmlApplicationContext(beans.xml);
final Student bean context.getBean(Student.class);
注意使用类型获取的时候一定要保证容器中只有一个 javabean 对象 4.注意点
bean 的配置spring 是使用反射调用对象的无参构造器实现的。所以必须提供无参构造器否则会出现如下错误 6.设计模式
6.1单例模式 概述属于创建型模式提供了创建对象的最佳方式。单例模式只能有一个单一的类 懒汉式单例模式:需要用的时候再去把对象创建出来
public class SingleObject {//线程不安全的懒汉式单例模式private static SingleObject instance;public static SingleObject getInstance(){if(instance null){instance new SingleObject();}return instance;}}
饿汉式单例模式不管你有没有我先创建出来
public class SingleObjectE {//线程不安全的饿汉式单例模式private static SingleObjectE instance new SingleObjectE();public static SingleObjectE getInstance(){return instance;}
}
6.2工厂模式 概述也是属于创建型模式目的也是提供创建对象的最佳方式 静态工厂
public class BeanFactory {public static Student getBean() {return new Student();}public static Object getBean(String name) {if (Student.equals(name))return new Student();else if(SingleObject.equals(name)) {return new SingleObject();}else{return new Object();}}}
实例工厂
public class BeanFactory {public Object getBean(){return new Student();}
}
7.bean 实例化 bean 交给 spring 创建底层究竟是怎么创建的 实例化 bean 三种方式 构造器(常用) 静态工厂方法 实例工厂方法 实现 FactoryBean最常用
7.1无参构造器实例化
新建 person 类底层是通过 clz.getDeclaredClasses() 获取构造器
public class Person {public Person(){}}
配置 Person bean
bean idperson classcn.wjcoder.domian.Person/bean 从容器中获取 bean
Test
public void testConstructorInit(){final ClassPathXmlApplicationContext context new ClassPathXmlApplicationContext(beans.xml);Person p (Person) context.getBean(person);}
注意修改构造器添加参数测试提示找不到无参构造器 7.2静态工厂方法实例化
创建 clintServer 类,提供静态工厂方法
public class ClientServer {//创建自身对象并且私有化private static ClientServer clientServer new ClientServer();private ClientServer() {}public static ClientServer createInstance(){return clientServer;}
}
配置bean 的 xml
bean idclientServer classcn.wjcoder.domian.ClientServer factory-methodcreateInstance/bean
获取 bean
Testpublic void testFactoryStaticMethodInit(){final ClassPathXmlApplicationContext context new ClassPathXmlApplicationContext(beans.xml);final ClientServer bean context.getBean(ClientServer.class);} 配置关系 7.3实例工厂方法实例化
创建实例工厂类
public class ClientServiceFactory {private static ClientService instance new ClientService();private ClientServiceFactory(){}public ClientService getInstance(){return instance;}
}
public class ClientService {
}
配置 bean
!-- 配置工厂--bean idclientFactory classcn.wjcoder.domian.ClientServiceFactory/bean
!-- 配置 clientService--bean idclientService factory-beanclientFactory factory-methodgetInstance/bean
获取bean
Testpublic void testFactoryInstanceMethodInit(){final ClassPathXmlApplicationContext context new ClassPathXmlApplicationContext(beans.xml);final ClientService bean context.getBean(ClientService.class);}
配置关系 7.4实现 FactoryBean实例化
创建员工类
public class Employee {public void check(){System.out.println(检查是否能够拿到员工类对象);}
}
创建员工 factory 类实现 FactoryBean
public class EmployeeFactory implements FactoryBeanEmployee {public Employee getObject() throws Exception {System.out.println(获取 emp 对象);return new Employee();}public Class? getObjectType() {return Employee.class;}public boolean isSingleton() {return false;}
}
配置工厂类(并没有直接配置 emp 类)
bean idemployee classcn.wjcoder.domian.EmployeeFactory/bean
Testpublic void testFactoryBeanInit(){final ClassPathXmlApplicationContext context new ClassPathXmlApplicationContext(beans.xml);final Employee emp (Employee)context.getBean(employee);emp.check();}
实现方法说明 isSingleton:如果是 true 返回单例的对象
public boolean isSingleton() {return true;}
getObject:进行对象创建的
public Employee getObject() throws Exception {System.out.println(获取 emp 对象);return new Employee();
}
三、DI
1.概述 概述Dependency Injection 依赖注入给对象设置属性曾经我们需要自己去创建 mapper 对象才能调用现在交给 spring 创建并且使用 DI 注入直接拿来用程序员就可以更加关注业务代码而不是创建对象 给对象设置属性方式 构造器 set 方法 spring 也是通过构造器以及set方法来实现属性设置
2.回顾问题 如果只给了 mapper 对象那么调用的时候会出现空指针 解决方式使用 DI 注入解决方案如下 3.构造器依赖注入
3.1创建学生类
public class Student {
}
3.2创建Mapper 接口以及实现类 创建 Mapper 接口 public interface StudentMapper {void insert(Student stu);int delete(Long id);
} 创建 Mapper 实现类 public class StudentMapperImpl implements StudentMapper{public void insert(Student stu) {System.out.println(保存学生信息);}
public int delete(Long id) {System.out.println(删除idid的学生信息);return 1;}
} 将 Mapper 交给容器管理 bean idstudentMapper classcn.wjcoder.di.mapper.StudentMapperImpl/bean
3.3创建 service 接口以及实现类 创建 service 接口 public interface IStudentService {void insert(Student stu);
int delete(Long id);
} 创建 service 实现类 public class StudentServiceImpl implements IStudentService {
private StudentMapper mapper;
public void insert(Student stu) {mapper.insert(stu);}
public int delete(Long id) {return mapper.delete(id);}
} 将 service 交给容器管理 bean idiStudentService classcn.wjcoder.di.service.impl.StudentServiceImpl/bean
3.4如果没有使用DI注入直接调用 会产生如下问题 4.5配置构造器注入属性
配置 service 构造器
public class StudentServiceImpl implements IStudentService {private StudentMapper mapper;public StudentServiceImpl(StudentMapper mapper){this.mapper mapper;}public void insert(Student stu) {mapper.insert(stu);}public int delete(Long id) {return mapper.delete(id);}
} 配置 xml
!-- 配置 service--bean idiStudentService classcn.wjcoder.di.service.impl.StudentServiceImplconstructor-arg namemapper refstudentMapper/constructor-arg/bean
!-- 配置 mapper--bean idstudentMapper classcn.wjcoder.di.mapper.StudentMapperImpl/bean
注意 name:构造器的参数名称 ref:配置文件中其它 bean 的名称 图示如下 3.6构造器配置多个引用类型参数
配置service
public class StudentServiceImpl implements IStudentService {private StudentMapper mapper;private UserMapper userMapper;public StudentServiceImpl(StudentMapper mapper,UserMapper userMapper){this.mapper mapper;this.userMapper userMapper;}public void insert(Student stu) {mapper.insert(stu);}public int delete(Long id) {userMapper.delete(id);return mapper.delete(id);}
} 创建mapper
public interface UserMapper {int delete(Long id);
}
创建mapper实现类
public class UserMapperImpl implements UserMapper{public int delete(Long id) {System.out.println(删除idid的用户信息);return 1;}
}
配置bean
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
!-- 配置 service--
bean idiStudentService classcn.wjcoder.di.service.impl.StudentServiceImplconstructor-arg namemapper refstudentMapper/constructor-argconstructor-arg nameuserMapper refuserMapper/constructor-arg
/bean
!-- 配置学生mapper--
bean idstudentMapper classcn.wjcoder.di.mapper.StudentMapperImpl/bean
!-- 配置用户mapper--
bean iduserMapper classcn.wjcoder.di.mapper.UserMapperImpl/bean
/beans
3.7构造器配置多个基本数据类型参数
配置service
public class StudentServiceImpl implements IStudentService {private String name;private int age;private StudentMapper mapper;private UserMapper userMapper;public StudentServiceImpl(String name,int age,StudentMapper mapper,UserMapper userMapper){this.name name;this.age age;this.mapper mapper;this.userMapper userMapper;}public void insert(Student stu) {mapper.insert(stu);}public int delete(Long id) {System.out.println( name:age);userMapper.delete(id);return mapper.delete(id);}
}
配置bean
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
!-- 配置 service--bean idiStudentService classcn.sycoder.di.service.impl.StudentServiceImplconstructor-arg nameuserMapper refuserMapper/constructor-argconstructor-arg namemapper refstudentMapper/constructor-argconstructor-arg typeint value18/constructor-argconstructor-arg typejava.lang.String valuesy/constructor-arg/bean
!-- 配置学生mapper--bean idstudentMapper classcn.sycoder.di.mapper.StudentMapperImpl/bean
!-- 配置用户mapper--bean iduserMapper classcn.sycoder.di.mapper.UserMapperImpl/bean
/beans
这种方式会存在参数覆盖的问题解决方式删除 type 添加 index 属性
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
!-- 配置 service--bean idiStudentService classcn.sycoder.di.service.impl.StudentServiceImplconstructor-arg nameuserMapper refuserMapper/constructor-argconstructor-arg namemapper refstudentMapper/constructor-argconstructor-arg index2 value18/constructor-argconstructor-arg index1 value1/constructor-argconstructor-arg typejava.lang.String valuesy/constructor-arg/bean
!-- 配置学生mapper--bean idstudentMapper classcn.sycoder.di.mapper.StudentMapperImpl/bean
!-- 配置用户mapper--bean iduserMapper classcn.sycoder.di.mapper.UserMapperImpl/bean
/beans
4.setter依赖注入 使用 set 方法实现属性的注入 使用 property 属性 name:属性名称 value:直接给值 ref:其它bean的引用
4.1创建员工类
public class Employee {
}
4.2创建 mapper 接口以及实现类 mapper 接口 public interface EmployeeMapper {int delete(Long id);
} mapper 实现类 public class EmployeeMapperImpl implements EmployeeMapper {public int delete(Long id) {System.out.println(删除当前员工id:id);return 1;}
}
4.3创建 servie 接口以及实现类 创建 service 接口 public interface IEmployeeService {int delete(Long id);
} 创建 service 接口实现类 public class EmployeeServiceImpl implements IEmployeeService {
private EmployeeMapper mapper;
public int delete(Long id) {return mapper.delete(id);}
}
4.4配置 setter 注入 配置bean
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd!-- 配置mapper实现类--
!-- 配置mapper--bean idempMapper classcn.sycoder.di.setter.mapper.EmployeeMapperImpl/bean
!-- 配置service--bean idempService classcn.sycoder.di.setter.service.impl.EmployeeServiceImpl/bean
/beans service 实现中提供 mapper 的setter 方法 public class EmployeeServiceImpl implements IEmployeeService {
private EmployeeMapper employeeMapper;
public int delete(Long id) {return employeeMapper.delete(id);}public void setEmployeeMapper(EmployeeMapper employeeMapper){this.employeeMapper employeeMapper;}
} 修改 beans.xml 通过 setter 注入 ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd!-- 配置mapper实现类--
!-- 配置mapper--bean idempMapper classcn.sycoder.di.setter.mapper.EmployeeMapperImpl/bean
!-- 配置service--bean idempService classcn.sycoder.di.setter.service.impl.EmployeeServiceImplproperty nameemployeeMapper refempMapper/property/bean
/beans 获取 service 执行 delete 方法 Testpublic void testSetDi(){final ClassPathXmlApplicationContext context new ClassPathXmlApplicationContext(DiSetterBeans.xml);final IEmployeeService empService (IEmployeeService) context.getBean(empService);empService.delete(2L);} setter 注入过程分析 4.5配置多个 setter 方法注入多个属性 给service 添加新的属性以及新的setter方法 public class EmployeeServiceImpl implements IEmployeeService {
private EmployeeMapper employeeMapper;
private UserMapper userMapper;
public int delete(Long id) {return employeeMapper.delete(id);}
public void setEmployeeMapper(EmployeeMapper employeeMapper){System.out.println(使用 setter 注入);this.employeeMapper employeeMapper;}
public void setUserMapper(UserMapper mapper){this.userMapper mapper;}
} 配置 userMapper bean ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd!-- 配置mapper实现类--
!-- 配置mapper--bean idempMapper classcn.sycoder.di.setter.mapper.EmployeeMapperImpl/bean
!-- 配置service--bean idempService classcn.sycoder.di.setter.service.impl.EmployeeServiceImplproperty nameemployeeMapper refempMapper/property/bean
!-- 配置 userMapper--bean iduserMapper classcn.sycoder.di.constructor.mapper.StudentMapperImpl/bean
/beans 通过 setter 注入 ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd!-- 配置mapper实现类--
!-- 配置mapper--bean idempMapper classcn.sycoder.di.setter.mapper.EmployeeMapperImpl/bean
!-- 配置service--bean idempService classcn.sycoder.di.setter.service.impl.EmployeeServiceImplproperty nameemployeeMapper refempMapper/propertyproperty nameuserMapper refuserMapper/property/bean
!-- 配置 userMapper--bean iduserMapper classcn.sycoder.di.constructor.mapper.UserMapperImpl/bean
/beans 获取 service 操作delete 方法 Testpublic void testSetterSDi(){final ClassPathXmlApplicationContext context new ClassPathXmlApplicationContext(DiSetterBeans.xml);final IEmployeeService empService (IEmployeeService) context.getBean(empService);empService.delete(2L);}
4.6使用 setter 注入简单类型 修改 service 类提供两个属性 int age 18,String name sy public class EmployeeServiceImpl implements IEmployeeService {
private EmployeeMapper employeeMapper;
private UserMapper userMapper;private String name;private int age;public void setName(String name){this.name name;}public void setAge(int age){this.age age;}
public int delete(Long id) {System.out.println(name : age);userMapper.delete(id);return employeeMapper.delete(id);}
public void setEmployeeMapper(EmployeeMapper employeeMapper){System.out.println(EmployeeMapper使用 setter 注入);this.employeeMapper employeeMapper;}
public void setUserMapper(UserMapper mapper){System.out.println(UserMapper使用 setter 注入);this.userMapper mapper;}
} 配置 xml 设置值 ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd!-- 配置mapper实现类--
!-- 配置mapper--bean idempMapper classcn.sycoder.di.setter.mapper.EmployeeMapperImpl/bean
!-- 配置service--bean idempService classcn.sycoder.di.setter.service.impl.EmployeeServiceImplproperty nameemployeeMapper refempMapper/propertyproperty nameuserMapper refuserMapper/propertyproperty namename valuesy/propertyproperty nameage value18/property/bean
!-- 配置 userMapper--bean iduserMapper classcn.sycoder.di.constructor.mapper.UserMapperImpl/bean
/beans 可能出现的问题 4.7setter 注入总结
对于引用数据类型来说使用
property name ref/property 对于简单数据类型
*property name value/property
5.集合注入
ListSetMapArrayProperties
5.1添加CollectiosDemo类
1.添加CollectiosDemo类1.添加CollectiosDemo类public class CollectionsDemo {private ListInteger list;private MapString,String map;private SetString set;private Properties properties;private int[] arr;public void print(){System.out.println(list:list);System.out.println(map:map);System.out.println(set:set);System.out.println(properties:properties);System.out.println(arr: Arrays.toString(arr));}public void setList(ListInteger list) {this.list list;}public void setMap(MapString, String map) {this.map map;}public void setSet(SetString set) {this.set set;}public void setProperties(Properties properties) {this.properties properties;}public void setArr(int[] arr) {this.arr arr;}
} 5.2配置 bean
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean idcollectionsDemo classcn.sycoder.collections.CollectionsDemo
!-- 注入 list--property namelistlistvalue1/valuevalue2/valuevalue3/value/list/propertyproperty namemapmapentry keyname valuesy/entry key age value18//map/propertyproperty namesetsetvaluejust some string/valuevaluejust string/value/set/propertyproperty namepropertiespropsprop keyurlexample.org/propprop keyuserroot/propprop keypassword123456/prop/props/propertyproperty namearrarrayvalue2/valuevalue2/valuevalue2/value/array/property/bean
/beans 如果不提供setter 方法会出现如下错误 6.自动装配
6.1概述 概述IOC容器根据bean所依赖的属性自动查找并进行自动装配。
6.2分类 不启用自动装配 byName 通过名称 byType 通过类型 constructor 通过构造器
6.3实操 准备工作 public class EmployeeService {private EmployeeMapperImpl employeeMapper;public int delete(Long id) {return employeeMapper.delete(id);}public void setEmployeeMapper(EmployeeMapperImpl employeeMapper){System.out.println(EmployeeMapper使用 setter 注入);this.employeeMapper employeeMapper;}
}
public class EmployeeMapperImpl{public int delete(Long id) {System.out.println(删除当前员工id:id);return 1;}
} 配置 bean 并且通过 bype 自动装配 ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean idempService classcn.sycoder.autowired.EmpService autowirebyType/beanbean idempMapperImpl classcn.sycoder.autowired.EmpMapperImpl/bean
/beans 配置 bean 并且通过 byName 自动装配 ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean idempService classcn.sycoder.autowired.EmpService autowirebyName/beanbean idempMapperImpl classcn.sycoder.autowired.EmpMapperImpl/bean
/beans 通过名称和类型的自动装配 byName 使用 id 或者是 name 别名 如果自动注入时有多个相同对象只能使用 byName byType 根据类型注入 通过 byType 注入要保证容器中只有一个 bean 对象否则会出现如下错误 注意 自动注入的优先级是低于 setter 和 构造器注入的 自动注入只能用于引用类型不能用于基本数据类型 推荐使用 byType 方式实现自动注入 注入流程 byType 根据 getClass 去注入 byName 根据属性名称去注入
7.bean scopes
常见的作用域
作用域说明singleton单例的prototype多例request请求session会话
单例 singleton修改对象变成多个实例的 注意容器模式就是以单例的方式创建对象的如果需要修改成非单例使用 scope 属性修改即可 以后开发中适合将那些bean对象交给 spring 管理 持久层 mapper 业务层 service 控制层 controller 单例bean会出现线程安全吗 判断bean 对象是否存储数据如果用来存储数据了会导致线程安全问题 使用局部变量做存储方法调用结束就销毁了所以不存在线程安全问题
8.bean 生命周期
8.1概述 概述生命周期就是一个对象从出生到死亡的过程
8.2使用用户类观察生命周期 创建用户类 public class User {private String name;public User(){System.out.println(构造器执行);}
public void setName(String name) {System.out.println(调用 set 方法);this.name name;}public void init(){System.out.println(调用 init 方法);}public void destroy(){System.out.println(调用销毁方法);}
} 配置 bean ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean iduser classcn.sycoder.lifecycle.User init-methodinit destroy-methoddestroyproperty namename valuesy/property/bean
/beans 获取 bean 出现如下问题没有打印销毁方法 原因 spring ioc 容器是运行在 jvm 虚拟机中的 执行 test 方法后 jvm 虚拟机开启spring 加载配置文件创建 bean 对象调用构造器以及 init 方法 test 方法执行完毕的时候 jvm 退出spring ioc 容器来不及关闭销毁 bean所以没有去调用 destroy 方法 解决办法手动关闭容器5.3BeanPostProcessor
自定义自己 bean 处理器
public class MyBeanPostProcessor implements BeanPostProcessor{public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {//bean 前置处理器System.out.println(bean 的前置处理器);return bean;}public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {System.out.println(bean 的后置处理器);//bean 后置处理器return bean;}
}
配置 bean
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean iduser classcn.sycoder.lifecycle.User init-methodinit destroy-methoddestroyproperty namename valuesy/property/beanbean classcn.sycoder.lifecycle.MyBeanPostProcessor/bean
/beans
5.4生命周期总结 bean 对象创建调用无参构造器 设置属性通过 setter 方法 init 方法前调用 bean 的前置处理器 bean 的 init 方法 bean 的后置处理器 对象可以正常使用 destroy 销毁方法 ioc 容器关闭 jvm 虚拟机的退出
四、容器执行点
1.整合 druid 连接池
添加依赖
dependencygroupIdcom.alibaba/groupIdartifactIddruid/artifactIdversion1.2.8/version
/dependency
1.1硬编码方式整合
新建德鲁伊配置
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean iddataSource classcom.alibaba.druid.pool.DruidDataSourceproperty nameusername valueroot/propertyproperty namepassword value123456/propertyproperty namedriverClassName valuecom.mysql.cj.jdbc.Driver/propertyproperty nameurl valuejdbc:mysql://localhost:3306/mybatis/property/bean
/beans
注意属性是通过 set 方法注入进来的
1.2使用占位符获取连接数据
建立 db.properties 配置文件
usernameroot
password123456
driverClassNamecom.mysql.cj.jdbc.Driver
urljdbc:mysql://localhost:3306/mybatis
配置引用db.propertiesbean iddataSource1 classcom.alibaba.druid.pool.DruidDataSourceproperty nameusername value${username}/propertyproperty namepassword value${password}/propertyproperty namedriverClassName value${driverClassName}/propertyproperty nameurl value${url}/property/bean
!-- 获取db.properties 配置文件--bean classorg.springframework.beans.factory.config.PropertyPlaceholderConfigurerproperty namelocation valuedb.properties/property/bean
引入 db.properties 缩写
context:property-placeholder locationdb.properties/
1.3注意事项 context:property-placeholder locationdb.properties/ 使用这个标签加载配置会加载到电脑系统配置 解决方式 给配置文件加上前缀变量
jdbc.usernameroot
jdbc.password123456
jdbc.driverClassNamecom.mysql.cj.jdbc.Driver
jdbc.urljdbc:mysql://localhost:3306/mybatis
username123
添加属性
context:property-placeholder system-properties-modeNEVER locationdb.properties/
加载多个配置文件可以用 * 代替
context:property-placeholder system-properties-modeNEVER location*.properties/
2.容器总结
2.1容器层级结构
按两次 shift 搜索 BeanFactory按 ctrl h 查看继承结构 2.2创建容器 BeanFactory 是容器顶层接口 ApplicationContext 核心接口 AbstractApplicationContext 抽象类提供了获取 bean 以及加载资源的功能 ClassPathXmlApplicationContext 装载bean的做初始化的
2.3bean 配置
bean iduser classcn.sycoder.lifecycle.User init-methodinit destroy-methoddestroy scope默认单例 autowirebyName lazy-initfalseproperty namename valuesy/property
/bean lazy-init:如果开启懒加载默认是调用时才创建bean init-method:初始化方法 destroy-method:销毁方法 scope:作用域单例原型 autowire自动注入 id:代表名称必须唯一 class:全限定类名
2.4di 注入
constructor-arg构造器注入 property : setter 注入集合注入