最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot中Bean生命周期自定義初始化和銷毀方法詳解

 更新時間:2024年01月24日 09:11:49   作者:浩澤學(xué)編程  
這篇文章給大家詳細(xì)介紹了SpringBoot中Bean生命周期自定義初始化和銷毀方法,文中通過代碼示例講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下

一、@Bean注解指定初始化和銷毀方法

創(chuàng)建BeanTest類,自定義初始化方法和銷毀方法。在@Bean注解的參數(shù)中指定BeanTest自定義的初始化和銷毀方法:銷毀方法只有在IOC容器關(guān)閉的時候才調(diào)用。

代碼如下:

/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: dog
 * @Description: TODO描述
 * @Date: 2024/1/21 22:55
 */
public class BeanTest {
    public BeanTest(){
        System.out.println("BeanTest被創(chuàng)建");
    }

    public void init(){
        System.out.println("BeanTest被初始化");
    }

    public void destory(){
        System.out.println("BeanTest被銷毀");
    }
}
/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: MyConfig
 * @Description: TODO描述
 * @Date: 2024/1/21 22:59
 */
@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
    @Bean(initMethod = "init",destroyMethod = "destory")
    public BeanTest beanTest(){
        return new BeanTest();
    }
}
//測試代碼
AnnotationConfigApplicationContext ct = new AnnotationConfigApplicationContext(MyConfig.class);
System.out.println("IoC容器創(chuàng)建完成");

在這里插入圖片描述

  • 可以看到調(diào)用的是自定義的方法,這里解釋一下,測試時,運(yùn)行完代碼塊程序就結(jié)束了,所喲IoC容器就被關(guān)閉,所以調(diào)用了IoC銷毀方法。同時可以看到初始化方法在對象創(chuàng)建完成后調(diào)用。
  • 當(dāng)組件的作用域?yàn)閱卫龝r在容器啟動時即創(chuàng)建對象,而當(dāng)作用域?yàn)樵停≒ROTOTYPE)時在每次獲取對象的時候才創(chuàng)建對象。并且當(dāng)作用域?yàn)樵?/strong>(PROTOTYPE)時,IOC容器只負(fù)責(zé)創(chuàng)建Bean但不會管理Bean,所以IOC容器不會調(diào)用銷毀方法。

二、實(shí)現(xiàn)InitializingBean接口和DisposableBean接口

看一下兩接口的方法:

public interface InitializingBean {

	/**
	 * Invoked by the containing {@code BeanFactory} after it has set all bean properties
	 * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
	 * <p>This method allows the bean instance to perform validation of its overall
	 * configuration and final initialization when all bean properties have been set.
	 * @throws Exception in the event of misconfiguration (such as failure to set an
	 * essential property) or if initialization fails for any other reason
	 * Bean都裝配完成后執(zhí)行初始化
	 */
	void afterPropertiesSet() throws Exception;
}
====================================================================
public interface DisposableBean {

	/**
	 * Invoked by the containing {@code BeanFactory} on destruction of a bean.
	 * @throws Exception in case of shutdown errors. Exceptions will get logged
	 * but not rethrown to allow other beans to release their resources as well.
	 */
	void destroy() throws Exception;

}

代碼如下:

/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: BeanTest1
 * @Description: TODO描述
 * @Date: 2024/1/21 23:25
 */
public class BeanTest1 implements InitializingBean, DisposableBean {
    @Override
    public void destroy() throws Exception {
        System.out.println("BeanTest1銷毀");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("BeanTest1初始化");
    }

    public BeanTest1() {
        System.out.println("BeanTest1被創(chuàng)建");
    }
}
=========================

@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
 @Bean
    public BeanTest1 beanTest1(){
        return new BeanTest1();
    }
}

在這里插入圖片描述

三、@PostConstruct(初始化邏輯)和@PreDestroy(銷毀邏輯)注解

  • 被@PostConstruct修飾的方法會在服務(wù)器加載Servlet的時候運(yùn)行,并且只會被服務(wù)器調(diào)用一次,類似于Serclet的inti()方法。
  • 被@PostConstruct修飾的方法會在構(gòu)造函數(shù)之后,init()方法之前運(yùn)行。
  • 被@PreDestroy修飾的方法會在服務(wù)器卸載Servlet的時候運(yùn)行,并且只會被服務(wù)器調(diào)用一次,類似于Servlet的destroy()方法。被@PreDestroy修飾的方法會在destroy()方法之后運(yùn)行,在Servlet被徹底卸載之前。

代碼如下:

/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: BeanTest2
 * @Description: TODO描述
 * @Date: 2024/1/21 23:32
 */
public class BeanTest2 {
    public BeanTest2(){
        System.out.println("BeanTest2被創(chuàng)建");
    }

    @PostConstruct
    public void init(){
        System.out.println("BeanTest2被初始化");
    }

    @PreDestroy
    public void destory(){
        System.out.println("BeanTest2被銷毀");
    }
}
========================
//
@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
 @Bean
    public BeanTest2 beanTest2(){
        return new BeanTest2();
    }
}

在這里插入圖片描述

四、BeanPostProcessor接口

BeanPostProcessor又叫Bean的后置處理器,是Spring框架中IOC容器提供的一個擴(kuò)展接口,在Bean初始化的前后進(jìn)行一些處理工作。

BeanPostProcessor的源碼如下:

public interface BeanPostProcessor {

	/**
	 * Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
	 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
	 * or a custom init-method). The bean will already be populated with property values.
	 * The returned bean instance may be a wrapper around the original.
	 * <p>The default implementation returns the given {@code bean} as-is.
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return the bean instance to use, either the original or a wrapped one;
	 * if {@code null}, no subsequent BeanPostProcessors will be invoked
	 * @throws org.springframework.beans.BeansException in case of errors
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
	 */
	@Nullable
	  //bean初始化方法調(diào)用前被調(diào)用
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
	 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
	 * or a custom init-method). The bean will already be populated with property values.
	 * The returned bean instance may be a wrapper around the original.
	 * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
	 * instance and the objects created by the FactoryBean (as of Spring 2.0). The
	 * post-processor can decide whether to apply to either the FactoryBean or created
	 * objects or both through corresponding {@code bean instanceof FactoryBean} checks.
	 * <p>This callback will also be invoked after a short-circuiting triggered by a
	 * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
	 * in contrast to all other BeanPostProcessor callbacks.
	 * <p>The default implementation returns the given {@code bean} as-is.
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return the bean instance to use, either the original or a wrapped one;
	 * if {@code null}, no subsequent BeanPostProcessors will be invoked
	 * @throws org.springframework.beans.BeansException in case of errors
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
	 * @see org.springframework.beans.factory.FactoryBean
	 */
	@Nullable
	//bean初始化方法調(diào)用后被調(diào)用
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

代碼如下:

/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: MyBeanPostProcess
 * @Description: TODO描述
 * @Date: 2024/1/21 23:40
 */
@Component
public class MyBeanPostProcess implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean);
        return bean;
    }
}
============================
@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
    @Bean
    public BeanTest1 beanTest1(){
        return new BeanTest1();
    }

    @Bean
    public BeanTest2 beanTest2(){
        return new BeanTest2();
    }
}

運(yùn)行結(jié)果如下:

BeanTest1被創(chuàng)建
postProcessBeforeInitialization...beanTest1=>com.dragon.restart1.BeanTest1@111d5c97
BeanTest1初始化
postProcessAfterInitialization...beanTest1=>com.dragon.restart1.BeanTest1@111d5c97
BeanTest2被創(chuàng)建
postProcessBeforeInitialization...beanTest2=>com.dragon.restart1.BeanTest2@29c17c3d
BeanTest2被初始化
postProcessAfterInitialization...beanTest2=>com.dragon.restart1.BeanTest2@29c17c3d
IoC容器創(chuàng)建完成
BeanTest2被銷毀
BeanTest1銷毀

通過上述運(yùn)行結(jié)果可以發(fā)現(xiàn)使用BeanPostProcessor的運(yùn)行順序?yàn)?/strong>:

IOC容器實(shí)例化Bean---->調(diào)用BeanPostProcessor的postProcessBeforeInitialization方法---->調(diào)用bean實(shí)例的初始化方法---->調(diào)用BeanPostProcessor的postProcessAfterInitialization方法。

總結(jié)

以上就是Bean生命周期自定義初始化和銷毀的講解。

到此這篇關(guān)于SpringBoot中Bean生命周期自定義初始化和銷毀方法詳解的文章就介紹到這了,更多相關(guān)SpringBoot Bean初始化和銷毀內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java?線程池狀態(tài)及狀態(tài)轉(zhuǎn)換

    java?線程池狀態(tài)及狀態(tài)轉(zhuǎn)換

    這篇文章主要介紹了java?線程池狀態(tài)及狀態(tài)轉(zhuǎn)換,Java里線程池的狀態(tài)和線程的狀態(tài)是完全不同的,具體有幾種狀態(tài)和哪些不同點(diǎn),下面文章詳細(xì)介紹,需要的小伙伴可以參考一下
    2022-05-05
  • 運(yùn)行Springboot測試類查詢數(shù)據(jù)庫數(shù)據(jù)顯示白網(wǎng)頁問題及解決方法

    運(yùn)行Springboot測試類查詢數(shù)據(jù)庫數(shù)據(jù)顯示白網(wǎng)頁問題及解決方法

    Spring Boot應(yīng)用未能啟動的原因是它沒有找到合適的數(shù)據(jù)庫配置具體來說,它需要一個數(shù)據(jù)源(DataSource),但未能在你的配置中找出,也沒有找到任何嵌入式數(shù)據(jù)庫(H2, HSQL 或 Derby),本文給大家分享運(yùn)行Springboot測試類查詢數(shù)據(jù)庫數(shù)據(jù)顯示白網(wǎng)頁問題及解決方法,一起看看吧
    2023-11-11
  • SpringBoot之Java配置的實(shí)現(xiàn)

    SpringBoot之Java配置的實(shí)現(xiàn)

    這篇文章主要介紹了SpringBoot之Java配置的實(shí)現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01
  • MinIO學(xué)習(xí)指南看這一篇就夠了

    MinIO學(xué)習(xí)指南看這一篇就夠了

    本文介紹了對象存儲、服務(wù)器磁盤和分布式文件系統(tǒng)的基本概念和區(qū)別,重點(diǎn)講解了MinIO的安裝、配置和基本操作,以及如何在SpringBoot項(xiàng)目中集成MinIO,感興趣的朋友一起看看吧
    2025-02-02
  • Gson之toJson和fromJson方法的具體使用

    Gson之toJson和fromJson方法的具體使用

    Gson是Google的一個開源項(xiàng)目,可以將Java對象轉(zhuǎn)換成JSON,也可能將JSON轉(zhuǎn)換成Java對象。本文就詳細(xì)的介紹了toJson和fromJson方法的具體使用,感興趣的可以了解一下
    2021-11-11
  • java 中動態(tài)代理機(jī)制的實(shí)例講解

    java 中動態(tài)代理機(jī)制的實(shí)例講解

    這篇文章主要介紹了java 中動態(tài)代理機(jī)制的實(shí)例講解的相關(guān)資料,希望通過本文大家能夠理解掌握動態(tài)代理機(jī)制,需要的朋友可以參考下
    2017-09-09
  • 詳解Java無需解壓直接讀取Zip文件和文件內(nèi)容

    詳解Java無需解壓直接讀取Zip文件和文件內(nèi)容

    本篇文章主要介紹了詳解Java無需解壓直接讀取Zip文件和文件內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • Java導(dǎo)致內(nèi)存泄漏的多種情況分析

    Java導(dǎo)致內(nèi)存泄漏的多種情況分析

    本文介紹了Java中常見的內(nèi)存泄漏情況,包括生命周期長的集合、未關(guān)閉的資源連接、ThreadLocal使用不當(dāng)、內(nèi)部類與外部類引用非靜態(tài)內(nèi)部類、監(jiān)聽器與回調(diào)注冊后沒有注銷,推薦使用MAT和VisualVM等工具進(jìn)行內(nèi)存泄漏排查,感興趣的朋友跟隨小編一起看看吧
    2026-01-01
  • springboot整合Mybatis-plus的實(shí)現(xiàn)

    springboot整合Mybatis-plus的實(shí)現(xiàn)

    這篇文章主要介紹了springboot整合Mybatis-plus的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • Feign遠(yuǎn)程調(diào)用Multipartfile參數(shù)處理

    Feign遠(yuǎn)程調(diào)用Multipartfile參數(shù)處理

    這篇文章主要介紹了Feign遠(yuǎn)程調(diào)用Multipartfile參數(shù)處理,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03

最新評論

米泉市| 吉首市| 龙游县| 合肥市| 古蔺县| 浮梁县| 永胜县| 阿鲁科尔沁旗| 湖南省| 巢湖市| 龙门县| 平顺县| 滨州市| 循化| 荔波县| 托里县| 阳高县| 鄂伦春自治旗| 遵化市| 沁阳市| 德保县| 昂仁县| 涞源县| 亳州市| 康平县| 调兵山市| 郓城县| 柳江县| 高要市| 百色市| 威海市| 宁陵县| 盱眙县| 铜鼓县| 凤阳县| 舞阳县| 黑龙江省| 大同县| 北流市| 杨浦区| 辽宁省|