Spring中xml标签lazy-init使用
1. 引言
bean的初始化有两种方式
- 实时初始化。Spring容器启用以后,即刻初始化
- 延迟初始化。代码中调用的时候,才会创建
Spring默认情况下,所有的bean都会被实时初始化。但是大量的bean实时初始化,会导致启动变慢。因此对于需要延迟初始化的bean,可以通过xml进行设置。
2. 延迟创建bean
修改springid.xml,如下
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="school" class="com.liwl.dev.SchoolImpl" lazy-init="true">
<property name="name" value="jiangnan"/>
<property name="address" value="江苏省无锡市滨湖区蠡湖大道1800号"/>
</bean>
<bean id="company" class="com.liwl.dev.CompanyImpl" lazy-init="true">
<property name="name" value="nsccwx"/>
<property name="address" value="江苏省无锡市滨湖区吟白路1号"/>
</bean>
<bean id="liwl001" class="com.liwl.dev.LiwanLiangImpl" depends-on="school,company" autowire="byType" lazy-init="true">
<property name="name" value="liwl" />
<property name="age" value="30"/>
</bean>
</beans>
修改LiwlTest.java
package com.liwl.dev;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class LiwlTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springdi.xml");
SchoolImpl school = (SchoolImpl) context.getBean("school");
System.out.println("school:"+school);
context.close();
}
}
运行结果
调用SchoolImpl bean 无参构造方法
school:[SchoolImpl bean],name:jiangnan,address:江苏省无锡市滨湖区蠡湖大道1800号
SchoolImpl bean 销毁
从结果看出,并没有创建LiwanLiangImpl的bean,说明是被延迟创建的
3. 依赖注入情况下的bean
修改springdi.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="school" class="com.liwl.dev.SchoolImpl" lazy-init="true">
<property name="name" value="jiangnan"/>
<property name="address" value="江苏省无锡市滨湖区蠡湖大道1800号"/>
</bean>
<bean id="company" class="com.liwl.dev.CompanyImpl" lazy-init="true">
<property name="name" value="nsccwx"/>
<property name="address" value="江苏省无锡市滨湖区吟白路1号"/>
</bean>
<bean id="liwl001" class="com.liwl.dev.LiwanLiangImpl" depends-on="school,company" autowire="byType">
<property name="name" value="liwl" />
<property name="age" value="30"/>
</bean>
</beans>
运行结果
调用SchoolImpl bean 无参构造方法
调用CompanyImpl bean 无参构造方法
调用LiwanLiangImpl bean 无参构造方法
school:[SchoolImpl bean],name:jiangnan,address:江苏省无锡市滨湖区蠡湖大道1800号
LiwanLiangImpl bean 销毁
CompanyImpl bean 销毁
SchoolImpl bean 销毁
说明此种情况,即便是被依赖的bean,school和company标注了lasy-init
,也还是因为被实时创建的beanliwanliang
依赖而实时创建