day 2----第一个spring程序
1. 软件版本
- JDK1.8及以上
- Maven3.5及以上
- IDEA2018+
- SpringFramework 5.1.4 (spring官网)
2. 环境搭建
- spring的jar包
#设置pom依赖 <!-- 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的配置文件
- 配置文件的存放位置:没有强制要求去放哪,任意位置
- 配置文件的命名:同样没有硬性要求。但是建议:applicationContext.xml
- 思考:之后应用spring框架时,需要设置配置文件的路径。
3. spring核心API
- ApplicationContext
作用:Spring提供的ApplicationContext这个工厂,用于对象的创建
好处:解耦合并且 ApplicationContext是接口类型
接口:可以屏蔽实现的差异
非web环境:ClassPathXmlApplicationContext (main junit)
web环境: XmlWebApplicationContext
- 重量级资源
- ApplicationContext工厂的实例化对象会占用大量内存
- 上一点会导致,不会频繁的创建工厂的实例化对象:一个应用只会创建一个工厂对象。
- 所以,必定会发生多线程并发访问该实例对象,故,必须是线程安全的。(源码中必定有synchronized)
4. 程序开发
- 创建类型
- 配置文件的配置 applicationContext.xml
<bean id="person" class="com.practice.spring.pojo.Person"/>
- 通过工厂类,获得对象
ApplicationContext
|-ClassPathXmlApplicationContext
@Test
public void test1() {
//获得对应的spring工厂对象
ApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml");
//通过工厂类获得 具体的bean对象
Person person = (Person) context.getBean("person");
System.out.println("person = " + person);
}