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
重量级资源
ApplicationContext工厂的对着占用大量内存(这里指ApplicationContext的实现类并非接口)
不会频繁的创建对象: 一个应用只会创建一个工厂对象
ApplicationContext工厂: 一定是线程安全的意味着可以被多线程并发访问
第一个Spring程序
程序开发
1. 创建类型
2. 配置⽂件的配置 applicationContext.xml<bean id="person" class="com.baizhiedu.basic.Person"/>
3. 通过⼯⼚类,获得对象ApplicationContext|- ClassPathXmlApplicationContextApplicationContext 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);