1 周期方法配置
1.1 周期方法概念
我们可以在组件类中定义方法,然后当IoC容器实例化和销毁组件对象的时候进行调用!这两个方法我们成为生命周期方法!
类似于Servlet的init/destroy方法,我们可以在周期方法完成初始化和释放资源等工作。
1.2 周期方法声明
public class BeanOne {
public void init(){
System.out.println("初始化");
}
public void clear(){
System.out.println("销毁");
}
}
1.3 周期方法配置
<?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">
<!-- init-method 初始化方法-->
<!-- destroy-method 销毁方法-->
<bean id="beanOne" class="com.lx.ioc_04.BeanOne" init-method="init" destroy-method="clear"></bean>
</beans>
2 组件作用域配置
2.1 Bean作用域概念
<bean
标签声明Bean,只是将Bean的信息配置给SpringIoC容器!
在IoC容器中,这些<bean
标签对应的信息转成Spring内部 BeanDefinition
对象,BeanDefinition
对象内,包含定义的信息(id,class,属性等等)!
这意味着,BeanDefinition
与类
概念一样,SpringIoC容器可以可以根据BeanDefinition
对象反射创建多个Bean对象实例。
具体创建多少个Bean的实例对象,由Bean的作用域Scope属性指定!
2.2作用域scope可选值
取值 | 含义 | 创建对象的时机 | 默认值 |
---|---|---|---|
singleton | 在 IOC 容器中,这个 bean 的对象始终为单实例 | IOC 容器初始化时 | 是 |
prototype | 这个 bean 在 IOC 容器中有多个实例 | 获取 bean 时 | 否 |
如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用): | |||
取值 | 含义 | 创建对象的时机 | 默认值 |
------- | ---------- | ------- | — |
request | 请求范围内有效的实例 | 每次请求 | 否 |
session | 会话范围内有效的实例 | 每次会话 | 否 |
2.3 作用域配置
public class BeanTwo {
}
<?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">
<!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建对象 -->
<!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 -->
<bean id="beanTwo" class="com.lx.ioc_04.BeanTwo" scope="singleton"/>
</beans>
@Test
public void test1(){
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-04.xml");
BeanTwo bean = classPathXmlApplicationContext.getBean(BeanTwo.class);
BeanTwo bean1 = classPathXmlApplicationContext.getBean(BeanTwo.class);
System.out.println(bean == bean1);//true
}