17做网站广州沙河,电子商务网站模板免费下载,国外网站搭建,wordpress编辑器视频教程✅作者简介#xff1a;2022年博客新星 第八。热爱国学的Java后端开发者#xff0c;修心和技术同步精进。 #x1f34e;个人主页#xff1a;Java Fans的博客 #x1f34a;个人信条#xff1a;不迁怒#xff0c;不贰过。小知识#xff0c;大智慧。 #x1f49e;当前专栏… ✅作者简介2022年博客新星 第八。热爱国学的Java后端开发者修心和技术同步精进。 个人主页Java Fans的博客 个人信条不迁怒不贰过。小知识大智慧。 当前专栏SSM 框架从入门到精通 ✨特色专栏国学周更-心性养成之路 本文内容一文吃透 Spring 中的IOC和DI 文章目录Spring 中 IOC 和 DI1. BeanFactory 容器2. ApplicationContext 容器3. Spring Bean定义4. IOC创建对象的方式5. Bean的自动装配6. spring中复杂对象的创建Spring 中 IOC 和 DI IoC 容器是 Spring 的核心也可以称为 Spring 容器。Spring 通过 IoC 容器来管理对象的实例化和初始化以及对象从创建到销毁的整个生命周期。 Spring 中使用的对象都由 IoC 容器管理不需要我们手动使用 new 运算符创建对象。由 IoC 容器管理的对象称为 Spring BeanSpring Bean 就是 Java 对象和使用 new 运算符创建的对象没有区别。 Spring 通过读取 XML 或 Java 注解中的信息来获取哪些对象需要实例化。Spring 提供 2 种不同类型的 IoC 容器即 BeanFactory 和 ApplicationContext 容器
1. BeanFactory 容器 BeanFactory 是最简单的容器由 org.springframework.beans.factory.BeanFactory 接口定义采用懒加载lazy-load所以容器启动比较快。BeanFactory 提供了容器最基本的功能配置文件加载时不会创建对象在获取bean时才会创建对象 为了能够兼容 Spring 集成的第三方框架如 BeanFactoryAware、InitializingBean、DisposableBean所以目前仍然保留了该接口。简单来说BeanFactory 就是一个管理 Bean 的工厂它主要负责初始化各种 Bean并调用它们的生命周期方法。BeanFactory 接口有多个实现类 org.springframework.beans.factory.xml.XmlBeanFactory最常见 使用 BeanFactory 需要创建 XmlBeanFactory 类的实例通过 XmlBeanFactory 类的构造函数来传递 Resource 对象。如下所示。
Resource resource new ClassPathResource(applicationContext.xml);
BeanFactory factory new XmlBeanFactory(resource); 2. ApplicationContext 容器 ApplicationContext 继承了 BeanFactory 接口由 org.springframework.context.ApplicationContext 接口定义对象在启动容器时加载。ApplicationContext 在 BeanFactory 的基础上增加了很多企业级功能例如 AOP、国际化、事件支持等。
ApplicationContext 接口有两个常用的实现类具体如下。
【1】ClassPathXmlApplicationContext 该类从类路径 ClassPath 中寻找指定的 XML 配置文件并完成 ApplicationContext 的实例化工作具体如下所示。
ApplicationContext applicationContext new ClassPathXmlApplicationContext(String configLocation);
配置文件加载则创建对象在上述代码中configLocation 参数用于指定 Spring 配置文件的名称和位置如 Beans.xml。
【2】FileSystemXmlApplicationContext 该类从指定的文件系统路径中寻找指定的 XML 配置文件并完成 ApplicationContext 的实例化工作具体如下所示。
ApplicationContext applicationContext new FileSystemXmlApplicationContext(String configLocation);二者的主要区别在于如果 Bean 的某一个属性没有注入使用 BeanFacotry 加载后第一次调用 getBean() 方法时会抛出异常而 ApplicationContext 则会在初始化时自检这样有利于检查所依赖的属性是否注入。 因此在实际开发中通常都选择使用 ApplicationContext只有在系统资源较少时才考虑使用 BeanFactory。
【3】spring容器加载多个配置文件
使用字符串参数逗号分隔
//加载spring的配置文件 启动spring容器
ApplicationContext ac new ClassPathXmlApplicationContext(config/student.xml,config/springConfig.xml);使用字符串数组
String[] config {config/student.xml,config/springConfig.xml};//加载spring的配置文件 启动spring容器ApplicationContext ac new ClassPathXmlApplicationContext(config);使用导入
?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.xsdimport resourcestudent.xml/import resourcespringConfig.xml/
/beans//加载spring的配置文件 启动spring容器ApplicationContext ac new ClassPathXmlApplicationContext(config/applicationContext.xml);3. Spring Bean定义 由 Spring IoC 容器管理的对象称为 BeanBean 根据 Spring 配置文件中的信息创建。 可以把 Spring IoC 容器看作是一个大工厂Bean 相当于工厂的产品如果希望这个大工厂生产和管理 Bean则需要告诉容器需要哪些 Bean以及需要哪种方式装配 Bean。
Spring 配置文件支持两种格式即 XML 文件格式和 Properties 文件格式。
Properties 配置文件主要以 key-value 键值对的形式存在只能赋值不能进行其他操作适用于简单的属性配置。XML 配置文件是树形结构相对于 Properties 文件来说更加灵活。XML 配置文件结构清晰但是内容比较繁琐适用于大型复杂的项目。 通常情况下Spring 的配置文件使用 XML 格式。XML 配置文件的根元素是 该元素包含了多个子元素 。每一个 元素都定义了一个 Bean并描述了该 Bean 如何被装配到 Spring 容器中 元素中可以包含很多属性其常用属性如下表所示。
属性名称描述idBean 的唯一标识符Spring 容器对 Bean 的配置和管理都通过该属性完成。id 的值必须以字母开始可以使用字母、数字、下划线等符号。namename 属性中可以为 Bean 指定多个名称每个名称之间用逗号或分号隔开。Spring 容器可以通过 name 属性配置和管理容器中的 Bean。class该属性指定了 Bean 的具体实现类它必须是一个完整的类名即类的全限定名。scope用于设定 Bean 实例的作用域属性值可以为 singleton单例、prototype原型、request、session 和 global Session。其默认值是 singletonconstructor-arg元素的子元素可以使用此元素传入构造参数进行实例化。该元素的 index 属性指定构造参数的序号从 0 开始type 属性指定构造参数的类型property元素的子元素用于调用 Bean 实例中的 setter 方法来属性赋值从而完成依赖注入。该元素的 name 属性用于指定 Bean 实例中相应的属性名ref 和 等元素的子元索该元素中的 bean 属性用于指定对某个 Bean 实例的引用value 和 等元素的子元素用于直接指定一个常量值list用于封装 List 或数组类型的依赖注入set用于封装 Set 类型的依赖注入map用于封装 Map 类型的依赖注入entry 元素的子元素用于设置一个键值对。其 key 属性指定字符串类型的键值ref 或 value 子元素指定其值init-method容器加载 Bean 时调用该方法类似于 Servlet 中的 init() 方法destroy-method容器删除 Bean 时调用该方法类似于 Servlet 中的 destroy() 方法。该方法只在 scopesingleton 时有效lazy-init懒加载值为 true容器在首次请求时才会创建 Bean 实例值为 false容器在启动时创建 Bean 实例。该方法只在 scopesingleton 时有效
4. IOC创建对象的方式
【1】无参构造器创建对象 默认
【2】有参构造创建对象
使用下标传递参数 !-- 使用索引匹配参数--
bean idstudent classcn.kgc.spring.entity.Studentconstructor-arg index0 value20/constructor-arg index1 value李四/constructor-arg index2 value20210814/constructor-arg index3 value2021/08/14/
/bean使用数据类型传递参数
!--使用数据类型匹配参数 有相同的参数类型可配合索引一起使用--bean idstudent classcn.kgc.spring.entity.Studentconstructor-arg typeint value20/constructor-arg typejava.lang.String index1 value李四/constructor-arg typejava.lang.String value20210814/constructor-arg typejava.util.Date value2021/08/14//bean通过属性名传递参数
!--使用属性名赋值--bean idstudent classcn.kgc.spring.entity.Studentconstructor-arg nameage value20/constructor-arg namename value李四/constructor-arg namestuNo value20210814/constructor-arg namebirth value2021/08/14 //bean【3】创建对象时属性的其它注入方式
set注入
bean idstudentService classcn.kgc.spring.service.StudentServiceImpl!-- 属性是引用类型 赋值时使用ref--property namestudentDao refstudentDao/!-- 属性是基本类型 String类型 Date类型 赋值时使用value --property nameage value20/property namestuName value张三/property nameprice value20.4/property namescore value80.3/property namebirth value2021/8/13/property namestr arrayvalue张三/valuevalue李四/valuevalue王五/value/array/propertyproperty namelislistvalue抽烟/valuevalue喝酒/valuevalue烫头/value/list/property!-- spring容器中组件默认都是单例的 全局共享一个对象--property namelis2listref beanstudentDao/refref beanstudentDao/refref beanstudentDao/ref/list/propertyproperty namebookssetvaluejava/valuevaluephp/valuevaluec#/value/set/propertyproperty namescoresmapentry keymath value89 /entryentry keyenglish value90 /entryentry keyjava value80 /entry/map/propertyproperty namemapmapentry key01 value-refstudentDao/entryentry key02 value-refstudentDao/entryentry key03 value-refstudentDao/entry/map/propertyproperty namepspropsprop keydrivercom.mysql.jdbc.Driver/propprop keyurljdbc:mysql:///mybatis/propprop keyusernameroot/propprop keypasswordrooot/prop/props/property/bean使用set注入每个属性必须含有对应的set方法否则无法进行属性的注入
Spring的依赖注入之p命名空间和c命名空间 p命名空间是set注入的一种快捷实现方式想要使用p命名空间注入需要注意一下几点。 实体类中必须有set方法实体类中必须有无参构造器默认存在必须导入p命名空间注入方式依赖。 xml依赖代码
xmlns:phttp://www.springframework.org/schema/p导入后即可使用
bean iduser classcom.yd.pojo.User p:age18 p:name老王/
!--需要有属性的set方法--
bean idstudent classcn.kgc.spring.entity.Student p:age20 p:namelisi p:birth2021/1/1 p:stuNo20210814001/beanc命名空间是构造器注入的一种快捷实现方式想要使用c命名空间需要注意一下几点。 实体类中必须存在有参构造器必须导入c命名空间注入方式依赖。 xml依赖代码
xmlns:chttp://www.springframework.org/schema/c导入后即可使用
bean iduser2 classcom.yd.pojo.User c:age23 c:name中王/!--需要有有参构造方法--
bean idstudent classcn.kgc.spring.entity.Student c:age30 c:name王五 c:birth1991/12/08 c:stuNo20210814001/bean类型转换器的使用 作用自定义注入参数和实体类中类型的匹配方式
import org.springframework.core.convert.converter.Converter;public class MyConverter implements ConverterString, Date {Overridepublic Date convert(String source) {SimpleDateFormat simpleDateFormat new SimpleDateFormat(yyyy-MM-dd);try {Date parse simpleDateFormat.parse(source);return parse;} catch (ParseException e) {e.printStackTrace();}return null;}
}xml文件配置
bean idconvert classcn.kgc.spring.basic.convert.MyConverter/beanbean idconversionService classorg.springframework.context.support.ConversionServiceFactoryBeanproperty nameconverterssetref beanconvert/ref/set/property
/bean5. Bean的自动装配
【1】autowirebyName在容器的上下文中寻找与类中属性对应的set方法名字相同的id属性值进行装配 bean idteacher classcn.kgc.spring.entity.Teacherproperty namename value李老师/property nameteaNo value001//beanbean idclassRoom1 classcn.kgc.spring.entity.ClassRoomproperty nameaddress value学思楼1楼/property nameclassNo value1//beanbean idstudent classcn.kgc.spring.entity.Student autowirebyName /bean【2】autowirebyType在容器的上下文中寻找与类中属性类型相同的Bean进行装配
bean idteacher classcn.kgc.spring.entity.Teacherproperty namename value李老师/property nameteaNo value001//beanbean idclassRoom1 classcn.kgc.spring.entity.ClassRoomproperty nameaddress value学思楼1楼/property nameclassNo value1//beanbean idstudent classcn.kgc.spring.entity.Student autowirebyType /bean【3】使用注解自动装配
导入context约束
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:phttp://www.springframework.org/schema/pxmlns:chttp://www.springframework.org/schema/cxmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd 开启注解支持
context:annotation-config/public class Student {Value(2021)private String stuNo;Value(wangwu)private String name;Value(20)private int age;Value(2021/12/08)private Date birth;Autowired private Teacher teacher;Resource private ClassRoom classRoom;}获取配置文件中的值
public class Aoo {Value(${test.boolean})private Boolean testBoolean;Value(${test.string})private String testString;Value(${test.integer})private Integer testInteger;Value(${test.long})private Long testLong;Value(${test.float})private Float testFloat;Value(${test.double})private Double testDouble;Value(#{${test.array}.split(,)})private String[] testArray;Value(#{${test.list}.split(,)})private ListString testList;Value(#{${test.set}.split(,)})private SetString testSet;Value(#{${test.map}})private MapString, Object testMap;} 配置文件 properties
test.booleantrue
test.stringabc
test.integer123
test.long123
test.float1.2345678123456
test.double1.2345678123456
test.array1,3,4,5,6,1,2,3
test.list1,3,4,5,6,1,2,3
test.set1,3,4,5,6,1,2,3
test.map{name:zhangsan, age:18}6. spring中复杂对象的创建
【1】FactoryBean
public class ConnectionFactoryBean implements FactoryBeanConnection {Overridepublic Connection getObject() throws Exception {Class.forName(com.mysql.jdbc.Driver);Connection connection DriverManager.getConnection(jdbc:mysql:///java2215?serverTimezoneUTC, root, root);return connection;}Overridepublic Class? getObjectType() {return Connection.class;}Overridepublic boolean isSingleton() {return false;}
}xml配置方式:
bean idconn classcn.kgc.spring.ioc.entity.ConnectionFactoryBean/bean【2】实例工厂
public class ConnectionFactoryBean {public Connection getConnection() throws Exception {Class.forName(com.mysql.jdbc.Driver);Connection connection DriverManager.getConnection(jdbc:mysql:///java2215?serverTimezoneUTCuseSSLfalse, root, root);return connection;}} xml配置方式
bean idconn classcn.kgc.spring.ioc.entity.ConnectionFactoryBean/bean
bean idconnection factory-beanconn factory-methodgetConnection/bean【3】静态工厂
public class ConnectionFactoryBean {public static Connection getConnection() throws Exception {Class.forName(com.mysql.jdbc.Driver);Connection connection DriverManager.getConnection(jdbc:mysql:///java2215?serverTimezoneUTCuseSSLfalse, root, root);return connection;}} xml配置方式
bean idconn classcn.kgc.spring.ioc.entity.ConnectionFactoryBean factory-methodgetConnection/bean码文不易本篇文章就介绍到这里如果想要学习更多Java系列知识点击关注博主博主带你零基础学习Java知识。与此同时对于日常生活有困扰的朋友欢迎阅读我的第四栏目《国学周更—心性养成之路》学习技术的同时我们也注重了心性的养成。