Spring Boot使用JSR250标准的@PostConstruct和@PreDestroy注解定制Bean的生命周期

在前面的博客中,我们使用了Spring自定义的两种方式(设置@Bean参数和实现接口)来定制Bean的生命周期。这篇博客将介绍如何使用JSR250标准定义的@PostConstrut和@PreDestroy注解来定制Bean的生命周期。

  • 创建Bean的类,并且注解对应的方法:
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Module {
    public Module(){
        System.out.println("The Module Bean is being created.");
    }

    //The PostConstruct annotation is used on a method that needs to be executed
    //after dependency injection is done to perform any initialization.
    @PostConstruct
    public void postConstruct(){
        System.out.println("The postConstruct method is calling.");
    }

    //The PreDestroy annotation is used on methods as a callback notification to signal
    // that the instance is in the process of being removed by the container.
    @PreDestroy
    public void preDestroy(){
        System.out.println("The preDestroy method is calling.");
    }
}
  • 代码上的英文注释为源码的注释,这里简单翻译一下:
  1. @PostConstrut:PostConstruct 为方法注解,被注解的方法在依赖注入后结束后执行。
  2. @PreDestroy:PreDestroy注解为方法注解,作为一个当实例被移出容器的回调信号(简单理解为在Bean被移出容器后调用被注解的方法)。
  3. 这里为了更好的演示,在构造器中打印了一句话。
  • 通过使用配置类和@Bean注解把Module实例注入容器:
import com.michael.annotation.demo.POJO.Module;
import org.springframework.context.annotation.*;

@Configuration
public class MyConfig {

    @Bean("Module1")
    @Scope("singleton")
    public Module module(){
        return new Module();
    }
}
  • 测试代码:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import static java.lang.System.out;
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
        out.println("The container has been initialized.");
         for(String name : applicationContext.getBeanDefinitionNames()){
             if(!name.contains("."))
                out.println(name);
        }
        out.println("The container has been destroyed.");
    }
}
  • 输出:
The Module Bean is being created.
The postConstruct method is calling.
2020-03-25 15:20:23.615  INFO 28087 --- [           main] c.m.annotation.demo.DemoApplication      : Started DemoApplication in 0.652 seconds (JVM running for 0.968)
The container has been initialized.
demoApplication
test
myConfig
personService
Module1
propertySourcesPlaceholderConfigurer
taskExecutorBuilder
applicationTaskExecutor
taskSchedulerBuilder
The container has been destroyed.
The preDestroy method is calling.
  • 这里可以看出,postConstruct方法是在Module类的构造器调用结束后被执行的。
发布了80 篇原创文章 · 获赞 4 · 访问量 3676
App 阅读领勋章
微信扫码 下载APP
阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 鲸 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览