第二章、第一个Spring软件 零基础学习Spring框架打卡第一天

第二章、第一个Spring软件

1.软件版本

1.JDK1.8+

2.Maven3.5+

3.IDEA2018+

4.SpringFramework 5.1.4

2.环境搭建

依赖查询 站:https://mvnrepository.com/;

Spring的jar包

设置pom依赖




    org.springframework
    spring-context
    5.1.4.RELEASE

Spring的配置文件

1.配置文件的放置位置:任意位置 没有硬性要求

2.配置文件的命名:没有硬性要求 建议:applicationContext.xml

思考:日后应用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.创建类型

2.配置文件的配置 applicationContext.xml

3.通过工厂类,获取对象

ApplicationContext

         |-ClassPathXmlApplicationContext

创建工厂类后,通过工厂类获取对象

//1.获取Spring的工厂
ApplicationContext ctx = new ClassPathXmlApplicationContext(“/applicationContext.xml”);
 //2.通过工厂类获取对象
Person person = (Person)ctx.getBean(“person”);

5.细节分析

名词解释

1.Spring创建的对象叫做bean或者组件(component)

Spring工厂的相关的方法:

传入id值和类名获取方法,不需要强制类型转换

// 通过这种方式获得对象,就不需要强制类型转换
Person person = ctx.getBean(“person”, Person.class);
System.out.println(“person = ” + person);

只指定类名,Spring的配置文件中只能有一个bean是这个类型

// 使用这种方式的话, 当前Spring的配置文件中 只能有一个bean class是Person类型
Person person = ctx.getBean(Person.class);
System.out.println(“person = ” + person);

获取Spring配置文件中所有bean表中的id值

// 获取的是Spring工厂配置文件中所有bean标签的id值  person person1
String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
    System.out.println(“beanDefinitionName = ” + beanDefinitionName);
}

根据类型获得Spring配置文件中的id值

// 根据类型获得Spring配置文件中对应的id值
String[] beanNamesForType = ctx.getBeanNamesForType(Person.class);
for (String id : beanNamesForType) {
    System.out.println(“id = ” + id);
}

用于判断是否存在指定id值得bean,不能判断name值

// 用于判断是否存在指定id值的bean,不能判断name值
if (ctx.containsBeanDefinition(“person”)) {
    System.out.println(true);
} else {
    System.out.println(false);
}

用于判断是否存在指定id值的bean,也可以判断name的值

// 用于判断是否存在指定id值的bean,也可以判断name值
if (ctx.containsBean(“p”)) {
    System.out.println(true);
} else {
    System.out.println(false);
}

配置文件中需要注意的细节

1.只配置class属性

a)上述这种配置,有没有id值 com.liulei.Person

b)应用场景:如果这个bean只需要使用一次,那么就可以省略id值

                   如果这个bean会使用多次,或者被其他bean引用则需要设置id值

2.name属性

作用:用于在Spring的配置文件中,为bean对象定义别名(小名)

相同:

1.ctx.getBean(“id|name”)—>object

2.

等效

区别:

1.别名可以定义多个,但是id属性只能有一个值

2.XML的id属性值,命名要求:必须要以字母开头,字母 数字 下划线 连字符 不能以特殊字符开头 /Person。

name属性的值,命名没有要求 /Person

name属性会应用在特殊命名场景下:/Person

XML发展到今天:id属性得限制,不存在 /Person

6.Spring工厂的底层实现原理)(简易版)

7.思考

问题:未来在开发过程中,是不是所有的对象,都会交给Spring工厂进行创建呢/p>

回答:理论上说:是的 但是有特例的:实体对象(entity)是不会交给Spring来创建的,交给持久层来进行创建的

文章知识点与官方知识档案匹配,可进一步学习相关知识Java技能树首页概览91673 人正在系统学习中

声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2022年6月22日
下一篇 2022年6月22日

相关推荐