這篇文章主要介紹了Spring Boot啓動及退出加載項的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧
在一個初春的下午,甲跟我說,要在Spring Boot啓動服務的時候,設置表自增的起始值。
於是我用屁股想了一下,不就是在main方法裏折騰嘛。
後來實際操作了一把,發現屁股被打了。
於是乎,找到官方文檔(以2.1.4爲例),找到這一段:
如果你需要在啓動SpringApplication後執行一些具體的代碼,你可以實現ApplicaitonRunner
或者CommandLineRunner
接口。兩個接口都實現了一個工作方式相同的run
方法,該方法僅會在SpringApplication.run(...)前執行。
唯一不同的是實現CommandLineRunner
接口的run
方法參數爲String
類型,而實現ApplicaitonRunner
的run
方法的參數則是需要ApplicationArguments
。官方文檔中有個例子供參考。
如果有多個ApplicaitonRunner
或者CommandLineRunner
接口的實現存在啓動順序,則可以使用org.springframework.core.Ordered
接口或者org.springframework.core.annotation.Order
註解的形式來給他們排序。
由於我沒有參數類型等的限制,所以用哪個接口都一樣,寫個跟官方不一樣的,於是代碼大概長這樣:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class InstructionStart implements ApplicationRunner { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JdbcTemplate template; @Override public void run(ApplicationArguments applicationArguments) throws Exception { String increment = "0"; logger.info("初始化遞增起始值爲:{}", increment); template.execute("ALTER TABLE `table` AUTO_INCREMENT = " + increment); } }
深刻的意識到腦子和屁股一樣重要。
寫完啓動項,那麼再把退出也說一下:
每一個SpringApplication
都應該向JVM
註冊一個鉤子函數來確保ApplicationContext
能優雅地關閉。使所有的標準Spring
生命週期回調(例如DisposableBean
接口和@PreDestroy
註解)都可用。
此外,如果你希望beans在調用SpringApplication.exit()
時返回特定的退出代碼,則可以實現org.springframework.boot.ExitCodeGenerator
接口,這些退出代碼會被傳給System.exit()
作爲返回的狀態碼。官方還給了個例子,就是下面這個。
@SpringBootApplication public class ExitCodeApplication { @Bean public ExitCodeGenerator exitCodeGenerator() { return () -> 42; } public static void main(String[] args) { System.exit(SpringApplication .exit(SpringApplication.run(ExitCodeApplication.class, args))); } }
當然,ExitCodeGenerator
也可以由異常來實現,當遇到一個這樣的異常時,Sprin Boot會返回實現了getExitCode()
方法的退出代碼。
後面退出部分翻譯地磕磕碰碰的,有不對的地方歡迎指正。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。