4_Spring Bean的初始化和销毁

Spring Bean的初始化和销毁

1. Bean 的初始化执行流程

Spring 提供了多种初始化和销毁的方法

编写相关Bean代码:

public class Bean1 implements InitializingBean {
    @PostConstruct
    public void init1(){
        System.out.println("初始化1");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化2");
    }

    public void int3(){
        System.out.println("初始化3");
    }
}

编写主方法测试:

@SpringBootApplication
public class A07Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(A07Application.class, args);
        context.close();
    }

    @Bean(initMethod = "init3") // 指定初始化方法
    public Bean1 bean1(){
        return new Bean1();
    }
}
初始化1
初始化2
初始化3

在初始化的时候首先会执行由基于扩展功能的@PostConstruct注解的方法,接着就是Spring内置接口的初始化方法,最后就是由@Bean注解里指定的初始化方法

2. Bean 的销毁执行流程

接下来看销毁方法:

是首先编写一个Bean:

public class Bean2 implements DisposableBean {

    @PreDestroy
    public void destroy1(){
        System.out.println("销毁1");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("销毁2");

    }

    public void destroy3(){
        System.out.println("销毁3");
    }
}

编写主方法:

@SpringBootApplication
public class A07Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(A07Application.class, args);
        context.close();
    }

    @Bean(destroyMethod = "destroy3")
    public Bean2 bean2(){
        return new Bean2();
    }
}

运行结果如下:

销毁1
销毁2
销毁3

在销毁Bean的时候首先会执行基于扩展功能的@PreDestroy指定的方法,其次是Spring内置接口功能的销毁,最后执行的是基于@Bean注解里面指定的销毁方法。

posted @ 2024-06-10 13:46  LilyFlower  阅读(3)  评论(0编辑  收藏  举报