Spring框架中bean的生命周期

使用@PostConstruct@PreDestroy注解在同一个配置类中执行bean的初始化前和销毁前的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Configuration
public class MyBeanPostProcessor {
@Bean
public String helloWorld() {
return "hello world";
}

@PostConstruct
public void init() {
System.out.println("我是初始化前执行的方法");
}

@PreDestroy
public void destroy() {
System.out.println("我是销毁前执行的方法");
}
}

上面的配置类中只定义了一个bean,且是字符串类型(方便举例),大部分情况下应该是返回一个对象。

使用@Bean(initMethod = "init", destroyMethod = "destroy")注解执行bean初始化前和销毁前的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
public class ConfigTest {
@Bean(initMethod = "init", destroyMethod = "destroy")
Test1 test1() {
return new Test1(); // 使用默认的无参构造器
}
}
// 定义Bean的内容,本质上是一个普通的java类
public class Test1 {
// 初始化前的执行方法
public void init() {
System.out.println("this is init method");
}
// 销毁前的执行方法
public void destroy() {
System.out.println("this is destroy method");
}
}
作者

彭凯

发布于

2021-08-09

更新于

2021-08-09

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.