Springboot中如何自定义init-method和destroy-method

如果我们想在初始化某个bean对象时自定义自己的init-method和destroy-method方法,我们可以使用通过Java配置文件方式注入要自定义自己init-method和destroy方法的bean,然后通过注解指定init-method和destroy-method,具体代码实现上可通过如下两种方式实现:

1.创建@Configuration注解类,在该类中初始化Bean对象,同时定义initMethod和destroyMethod

package com.mary;

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

/**
 * Created by gaoling on 2020/10/10.
 */
@Configuration
public class BeanConfig {

    @Bean(destroyMethod = "customDestroy", initMethod = "customInit")
    public SpringLifeCycleBean lifeCycleBean(){
        SpringLifeCycleBean lifeCycleBean = new SpringLifeCycleBean();
        return lifeCycleBean;
    }

}

2.在springboot的启动类中定义bean对象,同时定义initMethod和destroyMethod

package com.mary;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * Created by gaoling on 2020/10/10.
 */
@SpringBootApplication
public class AppStarter {

    public static void main(String[] args){
        SpringApplication.run(AppStarter.class, args);
    }

    @Bean(destroyMethod = "customDestroy", initMethod = "customInit")
    public SpringLifeCycleBean lifeCycleBean(){
        SpringLifeCycleBean lifeCycleBean = new SpringLifeCycleBean();
        return lifeCycleBean;
    }
}

你可能感兴趣的:(SpringBoot系列教程)