Spring創(chuàng)建Bean完成后執(zhí)行指定代碼的幾種實現(xiàn)方式
Spring中Bean創(chuàng)建完成后執(zhí)行指定代碼的幾種實現(xiàn)方式
在實際開發(fā)中經(jīng)常會遇到在spring容器加載完某個bean之后,需要執(zhí)行一些業(yè)務(wù)代碼的場景。比如初始化配置、緩存等。有以下幾種方式可以實現(xiàn)此需求
1、 實現(xiàn)ApplicationListener接口
實現(xiàn)ApplicationListener接口并實現(xiàn)方法onApplicationEvent()方法,Bean在創(chuàng)建完成后會執(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、 實現(xiàn)InitializingBean接口
實現(xiàn)InitializingBean接口并實現(xiàn)方法afterPropertiesSet(),Bean在創(chuàng)建完成后會執(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的某個方法上使用@PostConstruct注解,Bean在創(chuàng)建完成后會執(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í)行指定代碼的幾種實現(xiàn)方式的文章就介紹到這了,更多相關(guān)Spring Bean創(chuàng)建完成后執(zhí)行指定代碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Shell腳本實現(xiàn)SpringBoot項目自動化部署到Docker的操作指南
在日常項目開發(fā)中,我們經(jīng)常會將SpringBoot項目打包并部署到服務(wù)器上的Docker環(huán)境中,為了提升效率、減少重復(fù)操作,我們可以通過Shell腳本實現(xiàn)自動化部署,所以本文給大家介紹了使用Shell腳本實現(xiàn)SpringBoot項目自動化部署到Docker的操作指南,需要的朋友可以參考下2025-05-05
Java調(diào)用打印機的2種方式舉例(無驅(qū)/有驅(qū))
我們平時使用某些軟件或者在超市購物的時候都會發(fā)現(xiàn)可以使用打印機進行打印,這篇文章主要給大家介紹了關(guān)于Java調(diào)用打印機的2種方式,分別是無驅(qū)/有驅(qū)的相關(guān)資料,需要的朋友可以參考下2023-11-11
Liquibase結(jié)合SpringBoot使用實現(xiàn)數(shù)據(jù)庫管理功能
Liquibase 是一個強大的數(shù)據(jù)庫管理工具,它幫助你通過自動化管理數(shù)據(jù)庫的變更、版本控制、和回滾,簡化了開發(fā)中的數(shù)據(jù)庫遷移工作,這篇文章主要介紹了Liquibase結(jié)合SpringBoot使用實現(xiàn)數(shù)據(jù)庫管理,需要的朋友可以參考下2024-12-12
SpringBoot基于RabbitMQ實現(xiàn)消息可靠性的方法
RabbitMQ 提供了 publisher confirm 機制來避免消息發(fā)送到 MQ 過程中丟失,這種機制必須給每個消息指定一個唯一ID,消息發(fā)送到MQ以后,會返回一個結(jié)果給發(fā)送者,表示消息是否處理成功,本文給大家介紹了SpringBoot基于RabbitMQ實現(xiàn)消息可靠性的方法,需要的朋友可以參考下2024-04-04
Maven?Pom?文件中的隱式依賴導(dǎo)致Jar沖突問題
這篇文章主要介紹了Maven?Pom?文件中的隱式依賴導(dǎo)致Jar沖突問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

