Spring学习之路:环境搭建、核心API与配置文件细节

1.软件版本

1.JDK 1.8+

2.Maven3.5+

3.IDEA2018+

4.SpringFramework 5.1.5 
        官方网站 www.spring.io

 2.环境搭建

  • Spring的jar包

#设置 pom依赖 

可以去Maven中央仓库

Spring学习之路:环境搭建、核心API与配置文件细节_第1张图片


    org.springframework
    spring-context
    5.1.4.RELEASE
  •  Spring的配置文件

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

2.配置文件命名: 建议 applicationContext.xml

思考:日后应用Spring配置框架时,需要进行配置文件路径的设置。
Spring学习之路:环境搭建、核心API与配置文件细节_第2张图片

 3.Spring的核心API

  • ApplicationContext

作用:Spring提供的ApplicationContext这个工厂,用于对象的创建

好处:解耦合     

ApplicationContext接口类型

接口:屏蔽实现的类型 
(思考:为什么用接口类型:设计工厂时,考虑到工厂可能应用在不同的开发场景下,不同开发场景下有各自的特点,定义为接口,屏蔽不同工厂之间的差异)

非Web环境:ClassPathXmlApplicationContext(Main junit单元测试)

web环境:XmlWebApplicationContext(web应用)

Spring学习之路:环境搭建、核心API与配置文件细节_第3张图片

  • ApplicationContext重量级资源(对象占用比较多)

1.ApplicationContext工厂对象占用大量内存
2.不会频繁创建对象:一个应用创建一个工厂对象

思考:这种重量级只创建一个对象,可以被多线程资源,说明这种重量级资源时一定是线程安全的

 4.程序开发

1.创建类型

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

3.配置工厂类 获得对象

ApplicationContext

        -ClassPathXmlApplicationContext

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/applicationContext.xml"); /获得工厂
Person person =(Person)applicationContext.getBean("person");//强制类型转换 通过工厂 创建对象

 5.细节分析

  • 名词解释

Spring工厂创建的对象,叫做bean或者组件(componet)

  • Spring工厂的相关方法
 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/applicationContext.xml");
//        Person person= applicationContext.getBean("person",Person.class);
//        System.out.println(person);

        //用该方法获得对象 要求当前Spring的配置文件中,只能有一个
  • 配置文件中的细节

1.只配置class属性

a)上述这种配置 Spring有默认的id值

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

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

2.name属性
作用:用于在Spring的配置文件中,为Bean对象定义别名

相同:

        1.application.getBean("id|name")->object'

        2.

           等效
         

区别:

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

        2.application.containsBeanDefinition("")该方法智能判断id不能判断name

          application.containsBean都可以判断​​​​

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

Spring框架

1.通过ClassPathXmlApplicationContext工厂读取配置文件的信息

ApplicationContext application=new ClassPathXmlApplicationContext("配置文件地址");

2.获取bean标签的相关信息 包括id以及class

并通过反射的方式创建对象

Class clazz=Class.forName(class的值)

id的值=clazz.new instance();

3.通过反射的方式创建对象就等效于

Person person=new Person();

注意:

我们如果把Person类的构造方法声明为私有的,也是可以调用的(底层通过反射可以调用一个类型的私有属性和方法)
Spring学习之路:环境搭建、核心API与配置文件细节_第4张图片Spring学习之路:环境搭建、核心API与配置文件细节_第5张图片

7.思考

问题:未来开发过程中,是不是所有对象,都会交给Spring工厂来创建呢?

理论上来说是的,但是有特例:实体对象(entity)是不会交给Spring创建,由持久层框架创建。由于实体对象的创建涉及数据库的查询、映射和缓存,因此 Spring 不会直接管理它们,而是交给持久层框架负责持久化操作。

你可能感兴趣的:(Spring,spring,java,后端)