Spring5深入浅出篇:第一个Spring程序

Spring5深入浅出篇:第一个Spring程序

软件版本

1. JDK1.8+
2. Maven3.5+
3. IDEA2018+
4. SpringFramework 5.1.4
 官⽅⽹站 www.spring.io

环境搭建

  • Spring依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>5.1.4.RELEASE</version>
</dependency>
  • Spring配置文件

主要是有2点:

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

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

Spring核心API

  • ApplicationContext
作用:Spring提供的ApplicationContext这个工厂,用于对象的创建
好处:解耦合,也是Spring的核心工厂类

ApplicationContext接口类型

接口:屏蔽实现的差异,简单的来说就是方便拓展,基于不同环境的多个实现
非web环境(main方法或者junit单元测试中): ClassPathXMLApplication
web环境: XmlWebApplication

image.png

重量级资源

ApplicationContext工厂的对着占用大量内存(这里指ApplicationContext的实现类并非接口)
不会频繁的创建对象: 一个应用只会创建一个工厂对象
ApplicationContext工厂: 一定是线程安全的意味着可以被多线程并发访问

第一个Spring程序

程序开发

1. 创建类型
2. 配置⽂件的配置 applicationContext.xml
 <bean id="person" class="com.baizhiedu.basic.Person"/>
3. 通过⼯⼚类,获得对象
 ApplicationContext
 |- ClassPathXmlApplicationContext
 ApplicationContext ctx = new
ClassPathXmlApplicationContext("/applicationContext.xml");
 Person person = (Person)ctx.getBean("person");

可以发现大致流程跟我们之前设计的通用工厂基本一致,都是先创建类型,配置对应的名称和全限定类名,然后通过bean名称创建对象

细节分析

  • 名词解释
Spring⼯⼚创建的对象,叫做bean或者组件(componet)
  • Spring工厂相关方法
//通过这种⽅式获得对象,就不需要强制类型转换
Person person = ctx.getBean("person", Person.class);
System.out.println("person = " + person);
 
//当前Spring的配置⽂件中 只能有⼀个<bean class是Person类型
Person person = ctx.getBean(Person.class);
System.out.println("person = " + person);

如果applicationContext.xml中配置了多个bean class 为Person类型那么Spring会抛出异常

//获取的是 Spring⼯⼚配置⽂件中所有bean标签的id值 person person1
String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
 System.out.println("beanDefinitionName = " +
beanDefinitionName);
}
 
//根据类型获得Spring配置⽂件中对应的id值
String[] beanNamesForType = ctx.getBeanNamesForType(Person.class);
for (String id : beanNamesForType) {
 System.out.println("id = " + id);
}
 
//⽤于判断是否存在指定id值得bean
if (ctx.containsBeanDefinition("a")) {
 System.out.println("true = " + true);
}else{
 System.out.println("false = " + false);
}
 
//⽤于判断是否存在指定id值得bean
if (ctx.containsBean("person")) {
 System.out.println("true = " + true);
}else{
 System.out.println("false = " + false);
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全干程序员demo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值