Spring Boot启动及退出加载项

在一个初春的下午,甲跟我说,要在Spring Boot启动服务的时候,设置表自增的起始值。
因而我用屁股想了一下,不就是在main方法里折腾嘛。
后来实际操做了一把,发现屁股被打了。html

因而乎,找到官方文档(以2.1.4为例),找到这一段:spring

clipboard.png

若是你须要在启动SpringApplication后执行一些具体的代码,你能够实现ApplicaitonRunner或者CommandLineRunner接口。两个接口都实现了一个工做方式相同的run方法,该方法仅会在SpringApplication.run(...)前执行。app

惟一不一样的是实现CommandLineRunner接口的run方法参数为String类型,而实现ApplicaitonRunnerrun方法的参数则是须要ApplicationArguments。官方文档中有个例子供参考。ide

若是有多个ApplicaitonRunner或者CommandLineRunner接口的实现存在启动顺序,则可使用org.springframework.core.Ordered接口或者org.springframework.core.annotation.Order注解的形式来给他们排序。函数

因为我没有参数类型等的限制,因此用哪一个接口都同样,写个跟官方不同的,因而代码大概长这样:spring-boot

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);
    }
}

深入的意识到脑子和屁股同样重要。this

写完启动项,那么再把退出也说一下:spa

clipboard.png

每个SpringApplication都应该向JVM注册一个钩子函数来确保ApplicationContext能优雅地关闭。使全部的标准Spring生命周期回调(例如DisposableBean接口和@PreDestroy注解)均可用。翻译

此外,若是你但愿beans在调用SpringApplication.exit()时返回特定的退出代码,则能够实现org.springframework.boot.ExitCodeGenerator接口,这些退出代码会被传给System.exit()做为返回的状态码。官方还给了个例子,就是下面这个。code

@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()方法的退出代码。

后面退出部分翻译地磕磕碰碰的,有不对的地方欢迎指正。

原创不易,感谢支持。

相关文章
相关标签/搜索