13、生命周期-InitializingBean和DisposableBean

13、生命周期-InitializingBean和DisposableBean

  • InitializingBean接口
package org.springframework.beans.factory;

public interface InitializingBean {
    // 当BeanFactory创建完对象,并且设置完属性之后调用 = init
	void afterPropertiesSet() throws Exception;
}
  • DisposableBean接口
package org.springframework.beans.factory;

public interface DisposableBean {
    // 当对象销毁时调用
	void destroy() throws Exception;
}

13.1 新建Cat 实现接口

package com.hw.springannotation.beans;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * @Description TODO
 * @Author hw
 * @Date 2018/11/28 19:32
 * @Version 1.0
 */
public class Cat implements InitializingBean, DisposableBean {

    public Cat() {
        System.out.println("Cat constructor...");
    }

    public void destroy() throws Exception {
        System.out.println("Cat destroy...");
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("Cat afterPropertiesSet...");
    }
}

13.2 注入Cat

    @Bean
    public Cat cat() {
        return new Cat();
    }

13.3 测试

原文地址:https://www.cnblogs.com/Grand-Jon/p/10030819.html