- <?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">
- <!--
- init-method
- * 该方法是由spring容器执行
- * 在构造函数之后执行
- * 如果在构造函数之后,在调用方法之前要做一些工作,可以在init方法中完成
- destroy-method
- * 如果该bean是单例(默认就是singlton),则在spring容器关闭或者销毁的时候,执行该方法
- * 如果该bean是多例(scope="prototype"),则spring容器不负责销毁
- 说明:要想让spring容器控制bean的生命周期,那么该bean必须是单例
- 如果该bean是多例,该bean中还有资源,关闭资源的操作由程序员完成
- -->
- <bean id="helloWorld" class="cn.edu.initdestroy.HelloWorld" scope="prototype" init-method="init" destroy-
- method="destroy"></bean>
- </beans>
注意: 当一个bean是多例模式的情况下,lazy-init为false或者default无效。
- <!--
- 在默认情况下,spring创建bean是单例模式
- scope
- singleton 默认
- 单例
- 属性是共享的
- 一般情况下,把数据存放在方法中的变量中
- prototype
- 多例
- 当一个bean是多例模式的情况下,lazy-init为false或者default无效
- -->
- <bean id="helloWorld" class="cn.itcast.spring0909.scope.HelloWorld" scope="prototype" lazy-init="false"></bean>
- <!--
- 在启动spring容器的时候,spring容器配置文件中的类就已经创建完成对象了
- lazy-init
- default 即为 false
- true 在context.getBean的时候才要创建对象
- * 优点
- 如果该bean中有大数据存在,则什么时候context.getBean,什么时候创建对象
- 可以防止数据过早的停留在内存中,做到了懒加载
- * 缺点
- 如果spring配置文件中,该bean的配置有错误,那么在tomcat容器启动的时候,发现不了
- false 在启动spring容器的时候创建对象
- * 优点
- 如果在启动tomcat时要启动spring容器,
- 那么如果spring容器会错误,这个时候tomcat容器不会正常启动
- * 缺点
- 如果存在大量的数据,会过早的停留在内存中
- -->
- <bean id="helloWorld" class="cn.edu.spring0909.createobject.when.HelloWorl" lazy-init="true"></bean>
- <bean id="person" class="cn.edu.spring0909.createobject.when.Person" lazy-init="true"></bean>