1.版本
Spring版本:5.1.4
官方网站:www.spring.io
2.环境搭建
spring jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
spring配置文件
1.配置文件的放置位置:任意
2.配置文件的命名:任意 建议:applicationContext.xml
3.以后应用Spring框架时,需要进行配置文件路径的设置。
3.Spring的核心API
ApplicationContext
1.作用:Spring提供的 ApplicationContext这个工厂,用于对象的创建
2.好处:解耦合
ApplicationContext接口类型
1.接口:屏蔽实现的差异
2.非web环境:ClassPathXmlApplicationContext(main junit)不启用服务器
3.web环境: XmlWebApplicationContext
重量级资源
1.ApplicationContext工厂的对象占用大量内存
2.不会频繁的创建对象:一个应用只会创建一个工厂对象!
3.ApplicationContext工厂:一定是线程安全的(多线程并发访问)
4.程序开发
1.创建类型
public class Person {
}
2.配置文件的配置 applicationContext.xml
<!-- id属性 名字(唯一)相当于properties中的key-->
<!-- class属性 配置全限定类名 相当于properties中的value-->
<bean id="person" class="com.dy.basic.Person"/>
3.通过工厂类获得对象
ApplicationContext :ClassPathXmlApplicationContext
//1.获得Spring的工厂 AppletContext接口不能实例化 要new它的实现类
ApplicationContext ctx = new ClassPathXmlApplicationContext("/appletContext.xml");
// 2.通过工厂类获得对象 要强转 原因在上篇讲过
Person person = (Person) ctx.getBean("person");
5.细节分析
名词解释
1.Spring工厂创建的对象,叫做bean或者组件(componet)
2.Spring工厂其他的相关方法:
//1.此重载方法不需要强转
Person person1 = ctx.getBean("person", Person.class);
//2.当前Spring的配置文件中,只能有一个bean的class的Person类型
Person person2 = ctx.getBean(Person.class);
//3.bean(对象)定义的名字 获取的是Spring工厂配置文件中所有bean标签的id值
String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
//4.根据参数中的类型获取Spring配置文件中对应的id值
String[] beanNamesForType = ctx.getBeanNamesForType(Person.class);
//5.用于判断是否存在指定id值的bean 返回boolean型 不能判断name值
if (ctx.containsBeanDefinition("person")) {
System.out.println("true");
}
//6.用于判断是否存在指定id或者name值的bean
ctx.containsBean("person");
配置文件中的细节
1.只配置class属性
<bean class="com.dy.basic.Person"/>
Person person = ctx.getBean(Person.class);
通过此重载方法获得没有id值的对象
a)上述这种配置, 会有自动生成的id值
b)应用场景:如果这个bean只需要使用一次,那么就可以省略id值
//如果这个bean会使用多次,或者被其他bean引用则需要设置id值
2.name属性:
用于在Spring的配置文件中,为bean对象定义别名(小名)
与id相同点:
1.ctx.getBean("id/name")都可以获取到对象
2.<bean id="" class = ""
等效
<bean name="" class=""
区别:
//1.别名可以定义多个 但是id唯一
//2.XML的id属性值命名要求:必须以字母开头(以前)
// name属性命名要求:没有要求,随意
// 所以name属性应用在特殊命名的场景下:eg:/person
// XML发展到了今天:id属性的限制:不存在 /person id可以特殊字符命名开头
3.代码:
//5.用于判断是否存在指定id值的bean 返回boolean型 不能判断name值
if (ctx.containsBeanDefinition("person")) {
System.out.println("true");
}
//6.用于判断是否存在指定id或者name值的bean
ctx.containsBean("person");
============================================
6.Spring工厂的底层实现原理(简易版)
7.思考
问题:未来在开发过程中,是不是所有的对象,都会交给SpringI厂来创建呢?
回答:理论上是的,但是有特例:实体对象( entity)是不会交给Spring创建,它是由持久层框架进行创建。
实体对象封装数据库中表的数据,数据必须要操作数据库,Spring不知道数据库。
本系列文章从Spring5原理开始深入浅出,从工厂特性=>依赖注入–IOC=>AOP编程=>Spring事务=>纯注解开发。本文来自观看B站孙帅Spring教程后做的笔记。持续更新…