入门示例
Spring之所以可以实现模块的可插拔是支持依赖注入,所谓的依赖注入/控制反转就是不用new就可以创建对象。
需求:使用Spring框架不用new创建一个对象。
配置流程图
- 创建一个普通的类。
- 创建一个Spring配置文件,用于描述类与类之间的关系。
- 创建ApplicationContext容器对象根据Spring配置文件的描述,将对象创建并且放在Spring容器里面。
- 使用ApplicationContext容器对象的getBean方法,调用Spring容器里面的对象。
配置步骤说明
- 导入包
- 创建一个普通的类
- 创建一个Spring配置文件(去官方文档上拷贝约束)
- 编写一个测试类,使用ApplicationContext的子类对象根据配置文件创建容器。并且在容器里面获得创建的对象
配置步骤
第一步:搭建环境
1.创建一个Java项目
– 选中创建
–创建目录结构
2.导入包,String的基础支撑包和依赖的日志包复制到lib文件下,并且加入项目中
—导入Spring基础支撑包
–导入Spring依赖的日志包
第二步:创建配置文件
- 在项目的src下面创建配置文件applicationContext.xml中并完成配置文件的约束,约束查找位置(spring框架/docs/spring-framework-reference/html/beans.html)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
第三步:创建对象到容器里面
- 创建一个类
package cn.xc.spring.service;
public class HelloService {
public HelloService() {
System.out.println("构造函数执行了");
}
public void say() {
System.out.println("你好,世界");
}
}
- applicationContext.xml配置文件加入配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
<bean id="" class=""></bean>
Spring管理对象的标签,只要那个类在Spring配置,就被Spring框架管理
id:唯一标识
class :被管理类(对象)的全限定名
-->
<bean id="helloService" class="cn.xc.spring.service.HelloService"></bean>
</beans>
- 测试使用getBean获得容器中的对象。
package cn.xc.spring.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.xc.spring.service.HelloService;
public class SpringTest {
/*
* 需求: 创建HelloService 对象,并执行方法
*
* 1,直接new (传统做法),强耦合
*
* 2, 使用Spring 管理HelloService ,解耦
*
*/
@Test
public void testName() throws Exception {
//1,直接new (传统做法),强耦合 : 正控
//HelloService service = new HelloService();
//service.say();
//-------------------------------------
// 2, 使用Spring 管理HelloService ,解耦 : 控制反转
//读取Spring配置文件,启动Spring框架,创建Spring容器对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//ApplicationContext context = new FileSystemXmlApplicationContext("F:\\code\\javaee\\spring-demo01-start\\src\\applicationContext.xml");
//从Spring容器获取 HelloService对象 (getBean方法是Spring工厂用来获取对象用的)
//context.getBean(id,类型);
HelloService service = context.getBean("helloService", HelloService.class);
service.say();
}
}
通过代码得到,Spring框架果然不用new就可以创建对象。
Spring容器的两个实现
ClassPathXmlApplicationContext:通过classpath路径直接获得加载的xml文件(推荐使用)
FileSystemXmlApplicationContext:通过文件路径来获得加载的xml文件。
ApplicationContext类图结构图
Spring框架容器对象的继承体系
通过结构图可以看到,Spring容器顶级接口是BeanFactory,ApplicationContext是它的子接口。