今天就跟大家聊聊有關怎么在Spring Boot中啟動及退出加載項,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

如果你需要在啟動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()方法的退出代碼。
springboot一種全新的編程規范,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程,SpringBoot也是一個服務于框架的框架,服務范圍是簡化配置文件。
看完上述內容,你們對怎么在Spring Boot中啟動及退出加載項有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。