SpringBoot 启动成功初始化数据

本章节将介绍通过实现 CommandLineRunner 和 ApplicationRunner 接口,实现 Spring Boot 启动成功初始化数据。

如果你有一些资源需要在 Spring Boot 启动成功后才去加载,如:预加载配置、加载定时任务、初始化工作等。这些可以通过 Spring Boot 给我们提供的CommandLineRunner 接口和 ApplicationRunner 接口实现。

CommandLineRunner 接口

CommandLineRunner接口是在容器启动成功后的最后一步回调(类似开机自启动)。接口的源码如下:

package org.springframework.boot;

@FunctionalInterface
public interface CommandLineRunner {

    void run(String... args) throws Exception;

}

该接口只定义了一个 run() 方法,且该方法仅仅接收一个字符串数组。如果我们需要在 Spring Boot 启动成功后做些什么,如:初始化数据,需要实现该接口,实现 run 方法。例如:

package com.huangx.springboot.service;


import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

/**
 * SpringBoot启动完成后自动运行
 */
@Service
public class AfterServiceStartedOther implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("AfterServiceStartedOther");
        for(String arg : args) {
            System.out.println(arg);
        }
    }

}

在运行 Spring Boot 时,添加参数,如下图:

程序运行结果如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

  .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v2.0.1.RELEASE)

……

2020-07-20 23:04:31.759  INFO 16772 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729

……

AfterServiceStartedOther

name1

name2

name3

从上面实例可以知道,run 方法的参数实际是上就是我们运行程序传递的参数。

ApplicationRunner 接口

CommandLineRunner接口和ApplicationRunner 接口基本一样,区别在于两者接收的参数不一样。CommandLineRunner 的参数是最原始的参数,没有做任何处理;而ApplicationRunner的参数是ApplicationArguments,对原始参数做了进一步的封装。下面通过实例进行说明:

package com.huangx.springboot.service;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * SpringBoot启动完成后自动运行
 */
@Service
public class AfterServiceStarted implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("AfterServiceStarted");
        for(String name : args.getOptionNames()) {
            System.out.println(name + "=" + args.getOptionValues(name));
        }
    }

}

假如我们在这里配置了一些启动参数 --env=dev --level=debug,如下图:

然后运行程序,结果如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

  .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v2.0.1.RELEASE)

……

2020-07-20 23:14:16.307  INFO 21612 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729

……

AfterServiceStarted

level=[debug]

env=[dev]

如果使用 CommandLineRunner 实现上面实例,则 CommandLineRunner 只获取 --env=dev --level=debug 字符串。而 ApplicationRunner 可以将 --env=dev --level=debug 解析为 Key-Value,使得我们可以直接通过 key 来获取 value。

注意:ApplicationRunner 解析的参数必须使用“--”开头(双横线),否则不会解析。

设置 CommandLineRunner 和 ApplicationRunner 接口启动顺序

CommandLineRunner 和 ApplicationRunner 接口的工作方式类似,如果有多个启动回调接口实现类,我们还可以通过添加 @Order 注解指定顺序。

例如,我们将上面的 AfterServiceStarted 设置为第一个启动,AfterServiceStartedOther 设置为第二个启动。如下:

AfterServiceStarted.java

package com.huangx.springboot.service;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * SpringBoot启动完成后自动运行
 */
@Order(1)
@Service
public class AfterServiceStarted implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("AfterServiceStarted");
        for(String name : args.getOptionNames()) {
            System.out.println(name + "=" + args.getOptionValues(name));
        }
    }

}

AfterServiceStartedOther.java

package com.huangx.springboot.service;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

/**
 * SpringBoot启动完成后自动运行
 */
@Order(2)
@Service
public class AfterServiceStartedOther implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("AfterServiceStartedOther");
        for(String arg : args) {
            System.out.println(arg);
        }
    }

}

运行结果如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

  .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v2.0.1.RELEASE)

 ……

 2020-07-20 23:23:58.084  INFO 19048 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729

 ……

AfterServiceStarted

level=[debug]

env=[dev]

AfterServiceStartedOther

--env=dev

--level=debug

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 和 Quartz 结合可以方便地集成定时任务。如果需要在应用启动时从数据初始化数据,你可以采取以下步骤: 1. 首先,确保已经安装了 Spring Boot 和 Quartz 的依赖。在 `pom.xml` 文件中添加相应的库: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <!-- 可能需要的数据库连接池,取决于你的DB --> </dependency> ``` 2. 创建一个 Job 接口,比如 `MyJob.java`: ```java import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public interface MyJob extends Job { void execute(JobExecutionContext context) throws JobExecutionException; } ``` 3. 实现具体的 Job 类,例如 `MyJobImpl.java`,并在该类中加载数据数据: ```java @Service("myJob") public class MyJobImpl implements MyJob { @Autowired private YourDatabaseService databaseService; // 你需要注入的数据访问服务 @Override public void execute(JobExecutionContext context) throws JobExecutionException { databaseService.initializeData(); // 初始化数据操作 } } ``` 4. 在 Spring Boot 中配置 Quartz 定时器,通常会放在 `application.properties` 或 `application.yml` 中: ```properties quartz.job-store-type=jdbc quartz.dataSource.myDataSource.driver=com.mysql.jdbc.Driver quartz.dataSource.myDataSource.url=jdbc:mysql://localhost:3306/mydb quartz.dataSource.myDataSource.username=root quartz.dataSource.myDataSource.password=password quartz.jobStore.tableName=QUARTZ_JOB_DETAILS quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate quartz.jobStore.useProperties=true // 然后创建一个 scheduler bean,并设置 job 和触发器 spring.quartz.job-initializer=myJob // 使用自定义的初始化任务 ``` 5. 启动应用程序时,Spring Boot 会自动运行 Job 的初始化方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值