1、如果是单例模式,bean是在什么时候被实例化的呢?
我们在 PresonServiceImpl 类中添加一个带输出语句的构造函数,代码如下:
![]()
package com.learn.service.impl;
import com.learn.service.PresonService;
/**
* 业务层
* @author Administrator
*
*/
public class PresonServiceImpl implements PresonService {
public PresonServiceImpl(){
System.out.print("实例化");
}
/* (non-Javadoc)
* @see com.learn.service.impl.PresonService#save()
*/
@Override
public void save(){
System.out.println("保存! ");
}
}
单元测试类的代码如下:
![]()
package junit.test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.learn.service.PresonService;
public class TestSpring {
@Test
public void initContainerSpring() {
//实例化spring容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("com//learn//spring//learn1.xml");
}
}
测试运行,在控制台打印出了构造函数中的字符串:实例化。
说明:当容器实例化的时候就会对bean进行实例化。
2、当bean的作用域是prototype 时,即:
![]()
<bean id="personService" name="" class="com.learn.service.impl.PresonServiceImpl" scope="prototype"></bean>
bean是什么时候被实例化的?
当我们在依照上面的代码测试时,控制台没有打印出字符串。
我们在类TestSpring 的 initContainerSpring方法中添加,如下代码:
![]()
PresonService personService = (PresonService)ctx.getBean("personService");
在运行时,我们会发现控制台打印出了字符串。
也就是说,当bean的作用域是prototype 时, spring 容器调用getBean() 函数时才会实例化bean。
3、我们是否可以更改这种行为?
当是单实例的时候,我们将xml 文件代码改为如下:
![]()
<bean id="personService" name="" class="com.learn.service.impl.PresonServiceImpl" lazy-init="true"></bean>
lazy-init属性有三个值 default 、true、false,为 true时 表示bean 延迟初始化,为default 、false 则反之。
可以在 beans 节点元素上加 default-lazy-init 属性,设置是否要延迟初始化。但这是针对全局的。
4、如果当spring容器 实例化的时候就要执行某些操作的话,该如何?
在PresonServiceImpl 类中添加以下方法:
![]()
public void init(){
System.out.println("初始化");
}
修改 XML 文件的代码如下:
![]()
<bean id="personService" name="" class="com.learn.service.impl.PresonServiceImpl" init-method="init"></bean>
init-method 属性值是来自class 所指的类中的方法,即它的值为方法名。
表示当实例化spring容器后就执行init-method 属性所指定的方法。
5、bean 实例什么时候被销毁?
在PresonServiceImpl 类中添加以下方法:
![]()
public void destroy(){
System.out.print("销毁资源");
}
修改 XML 文件的代码如下:
![]()
<bean id="personService" name="" class="com.learn.service.impl.PresonServiceImpl" init-method="init" destroy-method="destroy"></bean>
destroy-method 属性值表示bean 实例销毁之前要执行的方法。
修改 TestSpring 类测试,代码如下:
![]()
package junit.test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.learn.service.PresonService;
public class TestSpring {
@Test
public void initContainerSpring() {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("com//learn//spring//learn1.xml");
ctx.close();
}
}