springboot启动加载数据

本文介绍如何使用SpringBoot通过实现CommandLineRunner接口,在应用启动时执行数据加载或其他操作。可以通过@Component和@Order注解确保此类被Spring管理并规定执行顺序。

springBoot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现加载一些数据或做一些事情。

创建实现接口 CommandLineRunner 的类,在run方法中写入操作。

@Component
public class MyRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println("服务启动执行,执行加载数据等操作");
    }
}

Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。

@Order 注解的执行优先级是按value值从小到大顺序。

@Component
@Order(value = 1)
public class MyRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println("服务启动执行,执行加载数据等操作");
    }
}
2017-01-17 18:08:50.135  INFO 5164 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8088 (http)
服务启动执行,执行加载数据等操作
2017-01-17 18:08:50.139  INFO 5164 --- [           main] com.zk.SpringbootSampleApplication       : Started SpringbootSampleApplication in 3.249 seconds (JVM running for 3.499)

 

 

转载于:https://my.oschina.net/zk875/blog/826691

在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应用启动时加载数据到内存,以便后续的业务逻辑使用。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值