温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Spring Boot中启动及退出加载项

发布时间:2021-05-19 15:57:13 来源:亿速云 阅读:192 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关怎么在Spring Boot中启动及退出加载项,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

怎么在Spring Boot中启动及退出加载项

如果你需要在启动SpringApplication后执行一些具体的代码,你可以实现ApplicaitonRunner或者CommandLineRunner接口。两个接口都实现了一个工作方式相同的run方法,该方法仅会在SpringApplication.run(...)前执行。

唯一不同的是实现CommandLineRunner接口的run方法参数为String类型,而实现ApplicaitonRunnerrun方法的参数则是需要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);
  }
}

深刻的意识到脑子和屁股一样重要。

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

怎么在Spring Boot中启动及退出加载项

每一个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是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

看完上述内容,你们对怎么在Spring Boot中启动及退出加载项有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI