唐僧喜欢小龙女

导航

Bean的生命周期通过注解的方式指定初始化和销毁的方法

1、通过指定init和destroy的方法

Spring 创建bean是通过反射创建的,先实例化bean然后再初始化bean

这里的初始化方法是在IOC容器把 bean 创建好后调用的,我原来通过实现接口BeanFactoryPostProcessor,已经给bean设置好了属性。

public class Person {

    private  int age;




    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


    public Person(){
        System.out.println("在实例化 person");
    }



    public void initMethod() {
        System.out.println("age 原来是 "+ this.getAge()+"===");

        System.out.println("调用initMethod方法");

        this.setAge(23);

    }

    public void destroy(){
        System.out.println("person 正在销毁");
    }
}


/**
 *
 *  生命周期的配置
 *
 */
@Configuration
public class MyConfigLifeCicly {


    @Bean(initMethod = "init",destroyMethod = "destroy")

}

2、实现 InitializingBean,DisposableBean 接口来设置

@Component
public class Cat implements InitializingBean,DisposableBean{

    private String name;





    public Cat(){
        System.out.println("cat  在创建中===");
    }


    @Override
    public void destroy() throws Exception {
        System.out.println("======cat  destroy 中========");
    }

    /**
     *
     * 属性设置好后在调用
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println( " 猫的 name is  " + this.getName());
        System.out.println("cat的  属性 设置好了,bean已经创建好了,正在调用初始化的方法==");
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3、使用 @PostConstruct 和 @PreDestroy 两个注解 的方式 

/**
 *
 *  @PostConstruct 这个注解标注在类的某个方法上,用来执行初始化的方法,也是在IOC容器把bean创建完后,以及bean的属性设置完
 *
 */
@Component
public class Cow {

    @PostConstruct
    public void init(){
        System.out.println("===================");
        System.out.println(" cow 在执行 初始化的方法");

    }

    public Cow(){
        System.out.println("===================");
        System.out.println("cow 在 创建中");
    }

    @PreDestroy
    public void destroy(){

        System.out.println("===================");
        System.out.println("cow 在 销毁 中");

    }
}

  

posted on 2021-06-05 20:06  与时具进&不忘初心  阅读(64)  评论(0编辑  收藏  举报