这里的初始化方法是在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")
}
@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;
    }
}
/**
 *
 *  @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 在 销毁 中");
    }
}
原文:https://www.cnblogs.com/gaohq/p/14853755.html