我對 Spring Boot 和開發非常陌生,所以我遇到了一個問題。我有一個舊專案需要遷移到 Spring Boot。原始的 main 方法具有超酷的多執行緒邏輯。據我了解,public static void main(String[] args) 是程式的入口點,現在在創建 Spring Boot 專案后,@springbootapplication 是入口點。如何訪問方法的原始邏輯?它應該以某種方式轉變嗎?我花了幾個小時尋找合適的解決方案,但沒有運氣。你能指點我嗎?任何幫助表示贊賞:)
uj5u.com熱心網友回復:
您必須使用@SpringBootApplication,但還需要修改主方法,例如:
@SpringBootApplication public class YourMainApplicationClass { public static void main(String[] args) { SpringApplication.run(YourMainApplicationClass.class, args); } }
這將啟動您的應用程式。
然后將您的 main 方法的原始代碼移動到一個新類,該類具有注釋 @Component。實作 CommandLineRunner,并覆寫 run 方法。所以像:
@Component public class YourOldMainClass implements CommandLineRunner { @Override public void run(String... args) throws Exception { //Your code here } }
當您的應用程式啟動時,spring 會將帶有注釋的“幾乎所有東西”加載到其容器中,因此您的 @Component 注釋類也應該被加載。具有覆寫 run 方法的 CommandLineRunner 將在啟動時自動呼叫您的方法。
此外,如果您使用它,請不要忘記在您的專案或構建自動化工具(如 Maven)旁邊包含必要的 Spring Boot jar。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/470360.html
上一篇:Thymeleaf spring保存新物件而不是更新
下一篇:多對多關系不會將新物體添加到表中