簡體   English   中英

Spring Boot:最初是數據解析

[英]Spring Boot: Initially data parsing

我正在尋找一種方法來在彈簧啟動應用程序啟動時讀取和解析大量數據,並且稍后可以在其他類中使用這些數據。

我從一個類DataRepository.java開始,並使用@Service注釋它以便以后能夠注入它。 我打算在這里讀取數據並將其注入我需要數據的任何其他類中。

但是我怎樣才能實現在app啟動時解析數據一次? 只有在解析完成后才能訪問spring boot應用程序。

使用@Service方法是100%合適的。

默認情況下,所有bean都是單例,因此如果你解析bean創建的數據(在構造函數中),它將只被解析一次,並且這個信息可以通過簡單的注入在其他bean中使用。

請注意,如果在數據解析期間必須使用其他bean ,則應確信所有bean都已完全構建。 為此你應該使用@jreznot提出的方法https//stackoverflow.com/a/51783858/5289288

您可以使用ContextStartedEvent並處理它:

@Component
public class ContextStartedListener implements ApplicationListener<ContextStartedEvent> {
    @Override
    public void onApplicationEvent(ContextStartedEvent cse) {
        System.out.println("Handling context start event. ");
    }
}

另見: https//www.baeldung.com/spring-events

您可以在任何bean上使用PostConstruct 例如

@Component
class DataLoad {

 ......
 ......


  @PostConstruct
  public void parseData() {

    ...... do your stuff here.......
  }
}

有了這個,parseData中的代碼將只被調用一次。 這是一種在場景中執行操作的常用方法,例如,當您希望在應用程序啟動時從數據庫加載某些配置數據時,只執行一次。 在這些情況下,您可以將存儲庫類@Autowired到同一個類,並在@PostConstruct方法中使用它並獲取數據

默認情況下,spring上下文中的所有bean都是單例。 Spring保證在上下文加載期間它會創建一個bean。 例如,如果您的應用程序中的上下文很少,則會為每個上下文創建一個實例。

如果您只有一個上下文,則可以使用以下方法:

  • 在構造函數中初始化數據。 數據將在bean創建實例后初始化並准備好使用。

     @Component public class DataRepository { public DataRepository() { ... init data } } 
  • 使用@Bean注釋和init方法。 允許您不要在數據存儲庫中堅持使用Spring,並在創建所有bean之后初始化數據。

      public class DataRepository { public void init() { ... init data } } @Configuration public class DataRepositoryConfiguration { @Bean(initMethod = "init") public DataRepository dataRepository() { return new DataRepository(); } 
  • 使用@Bean注釋並調用init方法。 允許您不要在數據存儲庫中堅持使用Spring,但@Autowired字段將保持未初始化狀態。

     public class DataRepository { public void init() { ... init data } } @Configuration public class DataRepositoryConfiguration { @Bean public DataRepository dataRepository() { DataRepository dr = new new DataRepository(); dr.init(); return dr; } } 
  • 使用@PostConstruct注釋。 創建所有bean后初始化數據。

     public class DataRepository { @PostConstruct public void init() { ... init data } } 

初始化期間拋出的異常將停止Spring的上下文初始化

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM