Spring創(chuàng)建Bean完成后執(zhí)行指定代碼的幾種實(shí)現(xiàn)方式
Spring中Bean創(chuàng)建完成后執(zhí)行指定代碼的幾種實(shí)現(xiàn)方式
在實(shí)際開(kāi)發(fā)中經(jīng)常會(huì)遇到在spring容器加載完某個(gè)bean之后,需要執(zhí)行一些業(yè)務(wù)代碼的場(chǎng)景。比如初始化配置、緩存等。有以下幾種方式可以實(shí)現(xiàn)此需求
1、 實(shí)現(xiàn)ApplicationListener接口
實(shí)現(xiàn)ApplicationListener接口并實(shí)現(xiàn)方法onApplicationEvent()方法,Bean在創(chuàng)建完成后會(huì)執(zhí)行onApplicationEvent方法
@Component public class DoByApplicationListener implements ApplicationListener<ContextRefreshedEvent> { public DoByApplicationListener() { System.out.println("DoByApplicationListener constructor"); } @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext().getParent() == null) { System.out.println("DoByApplicationListener do something"); } } }
2、 實(shí)現(xiàn)InitializingBean接口
實(shí)現(xiàn)InitializingBean接口并實(shí)現(xiàn)方法afterPropertiesSet(),Bean在創(chuàng)建完成后會(huì)執(zhí)行afterPropertiesSet()方法
@Component public class DoByInitializingBean implements InitializingBean { public DoByInitializingBean() { System.out.println("DoByInitializingBean constructor"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("InitByInitializingBean do something"); } }
3、 使用@PostConstruct注解
在Bean的某個(gè)方法上使用@PostConstruct注解,Bean在創(chuàng)建完成后會(huì)執(zhí)行該方法
@Component public class DoByPostConstructAnnotation { public DoByPostConstructAnnotation() { System.out.println("DoByPostConstructAnnotation constructor"); } @PostConstruct public void init(){ System.out.println("InitByPostConstructAnnotation do something"); } }
轉(zhuǎn)載自:https://segmentfault.com/a/1190000019622443?utm_source=tag-newest
到此這篇關(guān)于Spring中Bean創(chuàng)建完成后執(zhí)行指定代碼的幾種實(shí)現(xiàn)方式的文章就介紹到這了,更多相關(guān)Spring Bean創(chuàng)建完成后執(zhí)行指定代碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于JavaMail的Java實(shí)現(xiàn)簡(jiǎn)單郵件發(fā)送功能
這篇文章主要為大家詳細(xì)介紹了基于JavaMail的Java實(shí)現(xiàn)簡(jiǎn)單郵件發(fā)送功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09Java游戲俄羅斯方塊的實(shí)現(xiàn)實(shí)例
這篇文章主要介紹了Java游戲俄羅斯方塊的實(shí)現(xiàn)實(shí)例的相關(guān)資料,這里實(shí)現(xiàn)簡(jiǎn)單的俄羅斯方塊幫助大家學(xué)習(xí)理解基礎(chǔ)知識(shí),需要的朋友可以參考下2017-08-08SpringBoot?+?Redis如何解決重復(fù)提交問(wèn)題(冪等)
在開(kāi)發(fā)中,一個(gè)對(duì)外暴露的接口可能會(huì)面臨瞬間的大量重復(fù)請(qǐng)求,本文就介紹了SpringBoot + Redis如何解決重復(fù)提交問(wèn)題,具有一定的參考價(jià)值,感興趣的可以了解一下2021-12-12JPA之EntityManager踩坑及解決:更改PersistenceContext
這篇文章主要介紹了JPA之EntityManager踩坑及解決:更改PersistenceContext方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02