postconstruct_春天@PostConstruct和@PreDestroy

postconstruct

When we configure Spring Beans using dependency injection, sometimes we want to make sure everything is initialized properly before our bean starts serving the client requests. Similarly, when the context is destroyed, we may have to close some resources used by spring bean.

当我们使用依赖注入配置Spring Beans时 ,有时我们想确保在bean开始服务于客户端请求之前,一切都已正确初始化。 同样,当上下文被破坏时,我们可能不得不关闭spring bean使用的一些资源。

春天@PostConstruct (Spring @PostConstruct)

When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized.

当我们在Spring Bean中使用@PostConstruct注释对方法进行注释时,它会在初始化Spring Bean之后执行。

We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it’s part of JDK module javax.annotation-api. So if you are using this annotation in Java 9 or above, you will have to explicitly add this jar to your project. If you are using maven, then below dependency should be added to it.

我们只能使用一种带有@PostConstruct批注的方法。 该注释是Common Annotations API的一部分,也是JDK模块javax.annotation-api的一部分。 因此,如果您在Java 9或更高版本中使用此批注,则必须将该jar明确添加到项目中。 如果您使用的是maven,则应在其下面添加依赖项。

<dependency>
	<groupId>javax.annotation</groupId>
	<artifactId>javax.annotation-api</artifactId>
	<version>1.3.2</version>
</dependency>

If you are on Java 8 or lower version, then you won’t have to add above dependency.

如果您使用的是Java 8或更低版本,则不必添加上述依赖项。

春天@PreDestroy (Spring @PreDestroy)

When we annotate a Spring Bean method with PreDestroy annotation, it gets called when bean instance is getting removed from the context. This is a very important point to understand – if your spring bean scope is “prototype” then it’s not completely managed by the spring container and PreDestroy method won’t get called.

当我们使用PreDestroy注释对Spring Bean方法进行注释时,当从上下文中删除Bean实例时,将调用该方法。 这是一个非常重要的要点-如果您的spring bean作用域是“原型”,那么它就不会完全由spring容器管理,并且PreDestroy方法将不会被调用。

If there is a method named shutdown or close then spring container will try to automatically configure them as callback methods when bean is being destroyed.

如果有一个名为shutdownclose的方法,那么当bean被破坏时,spring容器将尝试自动将它们配置为回调方法。

Spring @PostConstruct和@PreDestroy示例 (Spring @PostConstruct and @PreDestroy Example)

Here is a simple spring bean with @PostConstruct and @PreDestroy methods.

这是带有@PostConstruct和@PreDestroy方法的简单Spring bean。

package com.journaldev.spring;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class MyBean {

	public MyBean() {
		System.out.println("MyBean instance created");
	}

	@PostConstruct
	private void init() {
		System.out.println("Verifying Resources");
	}

	@PreDestroy
	private void shutdown() {
		System.out.println("Shutdown All Resources");
	}

	public void close() {
		System.out.println("Closing All Resources");
	}
}

Notice that I have also defined a close method to check whether it gets called when our bean is destroyed or not.

注意,我还定义了一个close方法来检查是否在销毁我们的bean时调用它。

Here is my simple spring configuration class.

这是我简单的spring配置类。

package com.journaldev.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class MyConfiguration {
	
    @Bean
    @Scope(value="singleton")
    public MyBean myBean() {
	return new MyBean();
    }
	
}

I don’t need to explicitly specify my bean as a singleton but I will later change its value to “prototype” and see what happens with @PostConstruct and @PreDestroy methods.

我不需要显式地将我的bean指定为单例,但是稍后我将其值更改为“ prototype”,然后看看@PostConstruct和@PreDestroy方法会发生什么。

Here is my main class where I am creating spring context and getting few instances of MyBean.

这是我的主类,在其中创建spring上下文并获得少量MyBean实例。

package com.journaldev.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MySpringApp {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MyConfiguration.class);
		ctx.refresh();

		MyBean mb1 = ctx.getBean(MyBean.class);
		System.out.println(mb1.hashCode());

		MyBean mb2 = ctx.getBean(MyBean.class);
		System.out.println(mb2.hashCode());

		ctx.close();
	}

}

When we run above class, we get following output.

当我们在类上运行时,将得到以下输出。

MyBean instance created
Verifying Resources
1640296160
1640296160
Shutdown All Resources
Closing All Resources

So @PostConstruct method is called after the bean is instantiated. When the context is getting closed, it’s calling both shutdown and close method.

因此,在实例化bean之后调用@PostConstruct方法。 当上下文关闭时,它将同时调用shutdown和close方法。

具有原型范围的Spring @PostConstruct和@PreDestroy (Spring @PostConstruct and @PreDestroy with Prototype Scope)

Just change the scope value to prototype in MyConfiguration and run the main class. You will get output like below.

只需将范围值更改为MyConfiguration 原型并运行主类即可。 您将获得如下输出。

MyBean instance created
Verifying Resources
1640296160
MyBean instance created
Verifying Resources
1863374262

So it’s clear that spring container is initializing the bean on every request, calling its @PostConstruct method and then handing it over to the client. Spring is not managing the bean after that and in this case, the client has to perform all the resource cleanup by directly calling the PreDestroy method.

因此很明显,spring容器会在每个请求上初始化Bean,调用其@PostConstruct方法,然后将其移交给客户端。 之后,Spring将不再管理Bean,在这种情况下,客户端必须直接调用PreDestroy方法来执行所有资源清理。

摘要 (Summary)

@PostConstruct and @PreDestroy and important annotations to use with the spring bean lifecycle management. We can use them to verify that bean is properly initialized and then close all the resources when the bean is removed from the spring context.

@PostConstruct和@PreDestroy以及与Spring bean生命周期管理一起使用的重要注释。 我们可以使用它们来验证bean是否已正确初始化,然后在从spring上下文中删除bean时关闭所有资源。

GitHub Repository. GitHub Repository中检出完整的项目代码。

翻译自: https://www.journaldev.com/21206/spring-postconstruct-predestroy

postconstruct

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值