Bean的生命周期

star2017 1年前 ⋅ 2222 阅读

bean的生命周期

bean的创建--初始化--销毁的过程
IOC容器管理bean的生命周期
我们可以自定义初始化和销毁方法,容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法

构造(对象创建)
单实例:在容器启动的时候创建对象
多实例:在每次获取的时候创建对象

初始化:
对象创建完成,并赋值好,调用初始化方法。。。

销毁:
单实例:容器在关闭的时候进行销毁
多实例:容器不会管理bean的销毁,容器不会调用销毁方法。

第一种方式,@Bean里面的initMethod和destoryMethod的属性确定方法

实现步骤:
1)给需要创建bean的对象源代码里面添加初始化和销毁方法:
通过@Bean指定init-method和destory-method;

示例对象的源代码:
car

package com.debuggg.test1.main6;

public class Car {
    public Car(){
        System.out.println("car constructor...");
    }

    public void init(){
        System.out.println("car init...");
    }

    public void destory(){
        System.out.println("car destory...");
    }
}

示例配置类的代码:

package com.debuggg.test1.main6;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MainConfig {
//    @Scope("prototype")
    @Bean(initMethod = "init",destroyMethod = "destory")
    public Car car(){
        return new Car();
    }
}

示例IOC调用代码:

package com.debuggg.test1.main6;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class IOCTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        System.out.println("容器创建完成。。。");

        applicationContext.getBean("car");
        applicationContext.close();
    }
}
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: