當我們設定 Spring Beans時,我們有時想要確保一切都被正確啟動,直到我們的豆開始服務客戶的要求。
春天建设
当我们在Spring Bean中用@PostConstruct
的注释注释一个方法时,它在春豆初始化后就会执行。我们只能有一个以@PostConstruct
的注释注释的方法。这个注释是 Common Annotations API的一部分,也是JDK模块xjava.annotation-api
的一部分。因此,如果你在Java 9或更高版本中使用这个注释,你将不得不明确地将这个注释添加到你的项目中。
1<dependency>
2 <groupId>javax.annotation</groupId>
3 <artifactId>javax.annotation-api</artifactId>
4 <version>1.3.2</version>
5</dependency>
如果您使用的是 Java 8 或更低版本,则不必添加上面的依赖性。
春天预告片
当我们在 PreDestroy 注释中注释一个 Spring Bean 方法时,它会被调用,当 bean 实例被从文本中删除时,这是一个非常重要的点 - 如果你的 Spring Bean 范围( / 社区 / 教程 / 春豆 - 范围)是原型
,那么它不会被春豆完全管理,而PreDestroy
方法不会被调用。
春天 @PostConstruct 和 @PreDestroy 示例
这里有一个简单的春豆 @PostConstruct 和 @PreDestroy 方法。
1package com.journaldev.spring;
2
3import javax.annotation.PostConstruct;
4import javax.annotation.PreDestroy;
5
6public class MyBean {
7
8 public MyBean() {
9 System.out.println("MyBean instance created");
10 }
11
12 @PostConstruct
13 private void init() {
14 System.out.println("Verifying Resources");
15 }
16
17 @PreDestroy
18 private void shutdown() {
19 System.out.println("Shutdown All Resources");
20 }
21
22 public void close() {
23 System.out.println("Closing All Resources");
24 }
25}
请注意,我还定义了一种关闭
方法来检查当我们的豆子被摧毁时是否被调用,这是我的简单的(春季配置)( / 社区 / 教程 / 春季配置 - 注释)类。
1package com.journaldev.spring;
2
3import org.springframework.context.annotation.Bean;
4import org.springframework.context.annotation.Configuration;
5import org.springframework.context.annotation.Scope;
6
7@Configuration
8public class MyConfiguration {
9
10 @Bean
11 @Scope(value="singleton")
12 public MyBean myBean() {
13 return new MyBean();
14 }
15
16}
我不需要明確地指定我的豆子作為一個單曲,但我會稍後將其值變更為原型
,並看到 @PostConstruct 和 @PreDestroy 方法會發生什麼。
1package com.journaldev.spring;
2
3import org.springframework.context.annotation.AnnotationConfigApplicationContext;
4
5public class MySpringApp {
6
7 public static void main(String[] args) {
8 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
9 ctx.register(MyConfiguration.class);
10 ctx.refresh();
11
12 MyBean mb1 = ctx.getBean(MyBean.class);
13 System.out.println(mb1.hashCode());
14
15 MyBean mb2 = ctx.getBean(MyBean.class);
16 System.out.println(mb2.hashCode());
17
18 ctx.close();
19 }
20
21}
当我们跑高于班级时,我们会跟踪输出。
1MyBean instance created
2Verifying Resources
31640296160
41640296160
5Shutdown All Resources
6Closing All Resources
所以 @PostConstruct 方法被调用后,豆子被实例化. 当背景被关闭时,它正在调用关闭和关闭方法。
春天 @PostConstruct 和 @PreDestroy 使用原型范围
只需在MyConfiguration
中更改范围值为 原型,然后运行主类。
1MyBean instance created
2Verifying Resources
31640296160
4MyBean instance created
5Verifying Resources
61863374262
因此,很明显,春节容器在每个请求上初始化豆子,调用其 @PostConstruct 方法,然后将其交给客户端。
摘要
@PostConstruct 和 @PreDestroy 以及与春豆生命周期管理一起使用的重要注释,我们可以使用它们来验证春豆是否正确初始化,然后在春豆从春豆背景中删除时关闭所有资源。
您可以从我们的 GitHub 存储库查看完整的项目代码。