Spring_2_Spring中lazy-init和scope属性

2023-05-06,,

1)springTest类:

public class springTest {
@Test
public void instanceSpring() {
AbstractApplicationContext ctx = new
<span style="white-space:pre"> </span>ClassPathXmlApplicationContext("springXml/beans.xml");
<span style="white-space:pre"> </span>// 该实例输出结果为true:说明Spring容器中一个bean定义仅仅有一个对象实例
// 当bean的配置文件里设置scope="prototype"时,输出为false
// 说明:每次生成一个新的bean对象
<span style="white-space:pre"> </span>PersonService personService1 = (PersonService)ctx.getBean("personservice1");
PersonService personService2 = (PersonService)ctx.getBean("personservice1");
<span style="white-space:pre"> </span>System.out.println(personService1 == personService2);
}
}

2)Bean的XML配置文件:

<span style="font-size:14px;"><strong><?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-2.5.xsd"> <!-- 使用类构造器实例化Bean 推荐使用 -->
<!-- Spring容器中一个bean定义仅仅有一个对象实例,
默认情况会在容器启动时初始化bean,
但能够在 Bean节点中指定lazy-init="ture",
这时仅仅有第一次获取bean才会初始化bean.
假设想对全部的bean都实行延迟初始化,
能够在根节点beans设置default-lazy-init="true".
假设设置scope="prototype",则每次都会生成一个新的bean对象.
假设设置init-method="methodName",实例化对象时会调用该方法.
-->
<bean id="personService1" class="springDao.PersonServiceBean"
scope="prototype" init-method="init" ></bean>
</beans></strong></span>

Spring_2_Spring中lazy-init和scope属性的相关教程结束。

《Spring_2_Spring中lazy-init和scope属性.doc》

下载本文的Word格式文档,以方便收藏与打印。