栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

第二章--第一个Spring程序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第二章--第一个Spring程序

1.版本
Spring版本:5.1.4
官方网站:www.spring.io
2.环境搭建

spring jar包


    org.springframework
    spring-context
    5.1.4.RELEASE

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
    


    

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属性
    
        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. 

============================================

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

7.思考

问题:未来在开发过程中,是不是所有的对象,都会交给SpringI厂来创建呢?
回答:理论上是的,但是有特例:实体对象( entity)是不会交给Spring创建,它是由持久层框架进行创建。
实体对象封装数据库中表的数据,数据必须要操作数据库,Spring不知道数据库。

本系列文章从Spring5原理开始深入浅出,从工厂特性=>依赖注入–IOC=>AOP编程=>Spring事务=>纯注解开发。本文来自观看B站孙帅Spring教程后做的笔记。持续更新…

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353656.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号