Springboot启动时加载数据到内存中

25 篇文章 1 订阅
5 篇文章 0 订阅

前言

  一般来说,springboot工程环境配置放在properties文件中,启动的时候将工程中的properties/yaml文件的配置项加载到内存中。但这种方式改配置项的时候,需要重新编译部署,考虑到这种因素,今天介绍将配置项存到数据库表中,在工程启动时把配置项加载到内存中。
  springboot提供了两个接口:CommandLineRunner和ApplicationRunner。实现其中接口,就可以在工程启动时将数据库中的数据加载到内存。实现任意接口可实现以下场景:加载配置项到内存中;启动时将字典或白名单数据加载到内存(或缓存到redis中)。

一、CommandLineRunner实现

1、CommandLineRunner接口

1) 接口详解

在这里插入图片描述
  官方doc:

Interface used to indicate that a bean should run when it is contained within a SpringApplication.
Multiple CommandLineRunner beans can be defined within the same application context and can be orderedusing the Ordered interface or Order @Order annotation.

  这里是引用接口被用作将其加入spring容器中时执行其run方法。多个CommandLineRunner可以被同时执行在同一个spring上下文中并且执行顺序是以order注解的参数顺序一致。

If you need access to ApplicationArguments instead of the raw String arrayconsider using ApplicationRunner.

  如果你需要访问ApplicationArguments去替换掉字符串数组,可以考虑使用ApplicationRunner类。

2)代码演示

  在我们新建好工程后,为了简单我们直接使用Application类实现CommandLineRunner接口(或者新建类实现并使用@Component注解),这个类的注解@SpringBootApplication会为我们自动配置。

package com.skh.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class SpringbootApplication implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(SpringbootApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("服务已启动,执行command line runner。");

        for (int i = 0; i < args.length; ++i) {
            logger.info("args[{}]: {}", i, args[i]);
        }
    }
}


  启动服务,控制台查看日志如下,发现run()方法被正常地执行了:
在这里插入图片描述
  run()方法有个可变参数args,这个参数是用来接收命令行参数的,我们下面来加入参数来测试一下:
在这里插入图片描述
  重启,查看控制台日志,发现传入的参数已经打印出来:
在这里插入图片描述

2、ApplicationRunner接口

1)接口详解

在这里插入图片描述
  二者的官方javadoc一样,区别在于接收的参数不一样。CommandLineRunner的参数是最原始的参数,没有做任何处理。ApplicationRunner的参数是ApplicationArguments,是对原始参数做了进一步的封装。
  ApplicationArguments是对参数(main方法)做了进一步的处理,可以解析–name=value的,我们就可以通过name来获取value(而CommandLineRunner只是获取–name=value)。

在这里插入图片描述
可以接收–foo=bar这样的参数。
–getOptionNames()方法可以得到foo这样的key的集合。
–getOptionValues(String name)方法可以得到bar这样的集合的value。

2)代码演示

定义MyApplicationRunner类继承ApplicationRunner接口。

package com.skh.springboot;

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

import java.util.Arrays;

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("===MyApplicationRunner==="+ Arrays.asList(args.getSourceArgs()));
        System.out.println("===getOptionNames========"+args.getOptionNames());
        System.out.println("===getOptionValues======="+args.getOptionValues("param"));
        System.out.println("==getOptionValues========"+args.getOptionValues("developer.name"));
    }
}

然后加入启动参数
在这里插入图片描述
控制台查看日志打印
在这里插入图片描述

总结

1、CommandLineRunner和ApplicationRunner调用的时机是在容器初始化完成之后,立即调用。
2、CommandLineRunner和ApplicationRunner使用上没有区别,唯一区别是CommandLineRunner接受字符串数组参数,需要自行解析出健和值,ApplicationRunner的参数是ApplicationArguments,是对原始参数做了进一步的封装。
3、两个接口都可以使用@Order参数,支持工程启动后根据order声明的权重值来觉得调用的顺序(数字越小,优先级越高)。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot,可以通过使用初始化方法或者实现CommandLineRunner接口的方式来在应用启动时加载数据内存。 首先,我们可以在一个类上使用`@Component`注解或者实现`InitializingBean`接口,然后重写其`afterPropertiesSet()`方法,在该方法可以编写加载数据的逻辑。当Spring容器初始化该类时,`afterPropertiesSet()`方法会自动被调用。 ```java @Component public class DataLoader implements InitializingBean { @Autowired private DataRepository dataRepository; @Override public void afterPropertiesSet() throws Exception { // 在这里编写加载数据内存的逻辑 List<Data> dataList = loadDataFromDatabase(); dataRepository.loadDataToMemory(dataList); } private List<Data> loadDataFromDatabase() { // 从数据查询数据 // ... } } ``` 另外一种方式是实现`CommandLineRunner`接口,在该接口的`run()`方法编写加载数据的逻辑。Spring Boot启动时会扫描实现了`CommandLineRunner`接口的Bean并自动调用其`run()`方法。 ```java @Component public class DataLoader implements CommandLineRunner { @Autowired private DataRepository dataRepository; @Override public void run(String... args) throws Exception { // 在这里编写加载数据内存的逻辑 List<Data> dataList = loadDataFromDatabase(); dataRepository.loadDataToMemory(dataList); } private List<Data> loadDataFromDatabase() { // 从数据查询数据 // ... } } ``` 以上示例,我们通过`DataRepository`组件将从数据查询的数据加载到了内存,可以根据实际需求进行调整。通过以上两种方式,我们可以在Spring Boot应用启动时加载数据内存,以便后续的业务逻辑使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值