亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

springboot啟動(dòng)加載CommandLineRunner @PostConstruct問(wèn)題

 更新時(shí)間:2024年08月20日 10:15:49   作者:大旭123456  
這篇文章主要介紹了springboot啟動(dòng)加載CommandLineRunner @PostConstruct問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

springboot 啟動(dòng)加載

CommandLineRunner

在項(xiàng)目中,經(jīng)常有這樣的需求,我們需要在項(xiàng)目啟動(dòng)完立即初始化一些數(shù)據(jù)(比如緩存等),以便后面調(diào)用使用。spring boot可以通過(guò)CommandLineRunner接口實(shí)現(xiàn)啟動(dòng)加載功能。

新建一個(gè)Java文件,類需要用Component聲明下,需要實(shí)現(xiàn)CommandLineRunner接口,然后重寫run方法,在run方法內(nèi)編寫需要加載的內(nèi)容。

代碼如下:

package com.study.test.startup;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @Description: 初始化啟動(dòng)類
 * @Author: chen
 * @Date: Created in 2019/2/22
 */
@Component
public class InitStarter implements CommandLineRunner{

    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner example start");
    }
}

啟動(dòng)項(xiàng)目,運(yùn)行結(jié)果證明:CommandLineRunner會(huì)在服務(wù)啟動(dòng)之后被立即執(zhí)行

在項(xiàng)目中,我們可以寫一個(gè)類繼承CommandLineRunner接口,然后在實(shí)現(xiàn)方法中寫多個(gè)需要加載的方法,也可以寫多個(gè)類繼承CommandLineRunner,這些類之間,可以通過(guò)order注解(@Order(value=1))實(shí)現(xiàn)先后順序。

例子如下:

總結(jié):

  • CommandLineRunner會(huì)在服務(wù)啟動(dòng)之后被立即執(zhí)行。
  • CommandLineRunner可以有多個(gè),且多個(gè)直接可以用order注解進(jìn)行排序。

@PostConstruct

另一個(gè)需求是,在類加載的時(shí)候,為當(dāng)前類初始化一些數(shù)據(jù),那么可以使用@PostConstruct注解。

Servlet中增加了兩個(gè)影響Servlet生命周期的注解,@PostConstruct和@PreDestroy,這兩個(gè)注解被用來(lái)修飾一個(gè)非靜態(tài)的void()方法。

在一個(gè)類內(nèi),如果有構(gòu)造器(Constructor ),有@PostConstruct,還有@Autowired,他們的先后執(zhí)行順序?yàn)镃onstructor >> @Autowired >> @PostConstruct。

因?yàn)橐粋€(gè)有聲明注解的類文件(必須有聲明,這樣在項(xiàng)目初始化時(shí)候才會(huì)注入),在項(xiàng)目啟動(dòng)后,會(huì)對(duì)對(duì)象進(jìn)行依賴注入,而初始化的動(dòng)作會(huì)依賴于對(duì)象,所以假象上看,也類似于項(xiàng)目啟動(dòng)就會(huì)執(zhí)行的操作,因此,我們也可以通過(guò)這樣的形式,對(duì)數(shù)據(jù)進(jìn)行初始化。

說(shuō)明一下:

@PostConstruct更針對(duì)性于當(dāng)前類文件,而CommandLineRunner更服務(wù)于整個(gè)項(xiàng)目。所以在我們使用中,可根據(jù)自己的使用場(chǎng)景來(lái)進(jìn)行選擇用這兩種方式來(lái)實(shí)現(xiàn)初始化。

package com.study.test.postConstruct;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Description:
 * @Author: chen
 * @Date: Created in 2019/2/25
 */
@Component
public class Init {

    @PostConstruct
    private void init(){
        System.out.println("PostConstruct 注解 初始化數(shù)據(jù).");
    }
}

執(zhí)行結(jié)果:

說(shuō)明一下:

執(zhí)行結(jié)果可以看到,在項(xiàng)目還沒(méi)有啟動(dòng)成功的時(shí)候,@PostConstruct已經(jīng)執(zhí)行完了,因?yàn)锧PostConstruct是在Init類注入完成后立馬執(zhí)行的,它并不依賴于項(xiàng)目的啟動(dòng)。

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論