spring的Bean的生命周期

Bean的生命周期:

   定义    就是在xml文件中定义<bean>子标签,定义某个类的对象需要使用bean进行自动管理注入

   初始化   就是使用获取一个Bean容器context,然后使用context调用start方法进行初始化

   使用    就是获取对应bean中的实例

   销毁    就是bean不需要在使用的时候对bean相关的资源信息进行销毁

初始化

  方法一


  

  案例(使用了JUnit4进行测试)

 

package org.bean.example;

public class BeanLifeCycle {
    
    public void start(){
        System.out.println("bean start");
    }
    public void stop(){
        System.out.println("bean stop");
    }
}
package org.bean.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.util.test.UnitTestBase;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanLifeCycle extends UnitTestBase{
    
    public TestBeanLifeCycle() {
        super("classpath*:spring-life.xml");
    }
    
    @Test
    public void test(){
        super.getBean("beanLifeCycle");
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">

    <bean id="beanLifeCycle" class="org.bean.example.BeanLifeCycle" init-method="start" destroy-method="stop"></bean>
</beans>

 

  方法二


  案例

  

  

猜你喜欢

转载自www.cnblogs.com/myfaith-feng/p/9215142.html
今日推荐