Spring Boot:热部署与系统启动任务

    xiaoxiao2022-07-12  159

    Spring Boot:热部署与系统启动任务

    热部署系统启动任务不使用框架的解决方案SpringBoot的解决方案1.CommandLineRunner1,通过Program arguments传入参数2.命令行启动项目 2.ApplicationRunner

    热部署

    在代码修改完成以后,需要重新启动项目,花费大量时间 热部署就是为了解决这个问题 加入热部署 idea中使用热部署需要引入依赖

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency>

    在idea中,每当你编译的时候,就会自动重启 编译按钮为Build中的Build Project

    系统启动任务

    不使用框架的解决方案

    在项目启动阶段需要一些数据初始化操作,这些操作有一个共同的特点,只有在项目启动时进行,以后都不执行。 这种情况,一般定义一个ContextServlet的Listener来监听项目启动和销毁,来实现相应的数据初始化和销毁操作 如下

    public class OriginListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { //在这里做初始化操作 } @Override public void contextDestroyed(ServletContextEvent sce) { //在这里做数据备份操作 } }

    SpringBoot的解决方案

    SpringBoot中针对系统启动任务提供了两种解决方案

    1.CommandLineRunner

    创建类

    //注册为Spring容器中的一个Bean @Component //表示项目启动的优先级,因为在一个项目中,启动项目可能有很多个。如果不设置,默认情况下,优先级最低 @Order(100) public class OriginCommandLineRunner implements CommandLineRunner { @Override //当项目启动时,run方法被执行 //run方法的参数,来自于项目的启动参数,即项目入口类(Applicaion)中main方法的参数 public void run(String... args) throws Exception { System.out.println(Arrays.toString(args)+"123"); } }

    此时,当启动项目 时候,run方法会被执行,至于参数args可以通过两种方式传递

    1,通过Program arguments传入参数

    中的Program arguments

    2.命令行启动项目

    将项目打包,在命令行中启动项目,然后在启动时在命令行中传入参数 运行jar包 举例:

    2.ApplicationRunner

    使用ApplicationRunner

    @Component @Order(98) public class OriginApplicationRunner implements ApplicationRunner { @Override //相比于CommadnLineRunner参数不同 public void run(ApplicationArguments args) throws Exception { List<String> a= args.getNonOptionArgs();//获取命令行中无key的参数,相当于CommandLineRunner System.out.println(a); Set<String> b=args.getOptionNames();//获取所有的key/value形式的参数 for (String key:b){ System.out.println(key+":"+args.getOptionValues(key));//获取key/value形式的参数 } //获取命令行的所有参数 String[] c=args.getSourceArgs(); System.out.println(Arrays.toString(c)); } }

    中的Program arguments key/value使用–传输 –touxian=hahahah

    最新回复(0)