spring---生命周期
spring---生命周期
1.lazy-init="true/false/default";
2.init-method=" "//对象创建时调用
destroy-method=" "
问题:对象是什么时候创建的呢?
lazy-init="true/false/default";
配置文件:applicationContext.xml
<?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"> <bean id="p" class="com.Person" ></bean> <bean id="s" class="com.student" lazy-init="true"></bean> <bean id="w" class="com.Worker" lazy-init="false"></bean> </beans>
测试:
package com.life; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.Person; public class TestlifeDemo { @Test public void test01() { //启动spring容器,读取src文件下的applicationContext.xml ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); } }
测试结果:
由测试结果知:
当lazy-init=“false” 或默认不写时
对象实在spring容器启动时创建的
测试:
package com.life; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.Person; import com.Worker; import com.student; public class TestlifeDemo { @Test public void test01() { //启动spring容器,读取src文件下的applicationContext.xml ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Person p = (Person) ac.getBean("p"); student s = (student) ac.getBean("s"); Worker w = (Worker) ac.getBean("w"); } }
测试结果:
由测试结果知:
当lazy-init=“true” 时,调用spring容器调用getBean方法时,对象才创建出来
init-method=" " destroy-method=" "
配置文件:applicationContext.xml
<?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"> <bean id="p" class="com.Person" init-method="init" destroy-method="destroy"></bean> </beans>
person.java
package com; public class Person { public Person() { System.out.println("Person对象已创建完毕。。。"); } public void init() { System.out.println("初始化方法"); } public void destroy() { System.out.println("销毁方法"); } public void say() { System.out.println("hello world...."); } }
测试:
package com.life; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.Person; import com.Worker; import com.student; public class TestlifeDemo { @Test public void test01() { //启动spring容器,读取src文件下的applicationContext.xml ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Person p = (Person) ac.getBean("p"); p.say(); } }
测试结果:
总结:
bean对象什么时候创建出来的呢?
1.首先spring容器通过默认的构造函数创建对象
2. init-method="init" 调用初始化方法
3. talk()
4. destroy-method="destroy"调用销毁方法