一、添加 Maven 依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
二、创建实体类
public class IOCBean {
...
}
三、创建 Spring 配置文件
<?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="iocBean" class="chu.yi.bo.IOCBean"/>
</beans>
四、Bean 标签
作用:
用于配置对象交由 spring 框架来创建,默认情况下调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。
属性:
- id :给对象在容器中提供一个唯一标识。用于获取对象
- class :指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
- init-method :指定类中的初始化方法名称
- destroy-method :指定类中销毁方法名称
- scope :指定对象的作用范围
属性值 | 说明 |
---|---|
singleton | 单例,默认值 |
prototype | 多例 |
request | WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中 |
session | WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中 |
global session | WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么 globalSession 相当于 session |
五、测试
public void testSpring() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");
IOCBean aService = (IOCBean) applicationContext.getBean("iocBean");
}
六、Spring 容器
将实体类交由 Spring 框架管理后,Spring 容器负责这些类实例的创建、装配、销毁。BeanFactory 接口、ApplicationContext 接口是 Spring 框架的两个核心容器。ApplicationContext 接口继承 BeanFactory 接口。
两者区别:
容器 | 说明 |
---|---|
BeanFactory | 对象被使用时才会创建对象 |
ApplicationContext | 只要读取配置文件就会创建对象 |
ApplicationContext 接口实现类:
实现类 | 说明 |
---|---|
ClassPathXmlApplicationContext | 从类的根路径下加载配置文件 |
FileSystemXmlApplicationContext | 从磁盘路径上加载配置文件 |
AnnotationConfigApplicationContext | 使用注解配置容器对象时,需要使用此类来创建 spring 容器 |