使用 @PostConstruct、@Bean(initMethod=“”)注解指定初始化方法 、及实现InitializingBean接口 在 Spring Bean 完成初始化后进行一些响应的操作

如果需要在 某个特定的bean 被初始化后,执行一些代码逻辑,可以使用@PostConstruct、@Bean(initMethod=“”)注解指定初始化方法 、及实现InitializingBean接口 来完成这类特定的需求。

该三种方式,是在 特定bean 被初始化完成后(bean初始化完成,不同于 spring 整个容器 初始化完成),执行的特定业务逻辑。

1.使用 @PostConstruct 针对 Bean的初始化完成之后做一些事情:

@PostConstruct注解一般放在Bean的方法上,一旦Bean初始化完成之后,将会调用这个方法,代码如下:

@Component
@Slf4j
public class SimpleExampleBean {

  @PostConstruct
  public void init(){
    log.debug("Bean初始化完成,调用...........");
  }
}

2.使用 @Bean(initMethod="")注解中指定initMethod 初始化方法

这种方式和 @PostConstruct比较类似,同样是指定一个方法在Bean初始化完成之后调用

@Slf4j
@Configuration
public class SimpleExampleBean {


    public void init(){
       log.debug("SimpleExampleBean 初始化完成,调用...........");
    }


    @Bean(initMethod = "init")
    public SimpleExampleBean simpleExampleBean(){
        return new SimpleExampleBean();
    }
 

 
}



3.InitializingBean接口

InitializingBean的用法基本上与 @PostConstruct一致,只不过相应的 Bean需要实现 afterPropertiesSet方法,代码如下:

@Slf4j
@Component
public class SimpleExampleBean implements InitializingBean {

  @Override
  public void afterPropertiesSet()  {
      log.debug("Bean初始化完成,调用...........");
  }
}

顺便说一下:

spring 中提供了这三种 方式, 针对 某一个特定 的bean 被初始化后的一些操作,

还提供了 在 整个spring容器初始化后执行一些操作,包括: 实现监听容器刷新完成扩展点 ApplicationListener<ContextRefreshedEvent>、实现 CommandLineRunner接口、实现ApplicationRunner接口(这两个 Runner接口是springboot 中提供的)。

扫描二维码关注公众号,回复: 14174796 查看本文章
整个容器初始化完成后执行 特定bean初始化后执行 提供者
@PostConstruct spring
@Bean(initMethod="") spring
实现InitializingBean接口 spring
实现ApplicationEvent和 ApplicationListener 接口 spring
实现CommandLineRunner接口 springboot
实现ApplicationRunner接口 springboot

猜你喜欢

转载自blog.csdn.net/jsxztshaohaibo/article/details/121899283
今日推荐