ApplicationRunner实现“项目启动就执行“功能

ApplicationRunner

Application是个接口,常用于项目启动后(SpringApplication.run()执行结束),立马执行某些逻辑。可用于项目的准备工作,比如加载配置文件,加载执行流,定时任务等。

如何使用Application

在这里插入图片描述

  1. 实现ApplicationRunner接口,重写run方法,定义具体的执行逻辑;
  2. @Order注解,用于决定多个bean的执行顺序;按照值从小到大执行;

扩展CommandLineRunner

CommandLineRunner与ApplicationRunner接口类似,区别是,CommandLineRunner接口中的run方法接收的参数为String数组。

在这里插入图片描述

在Spring Boot项目启动时将数据库中的数据缓存至Map,可以使用Spring Boot提供的ApplicationRunner或CommandLineRunner接口,在项目启动完成后执行指定的逻辑。 具体实现步骤如下: 1. 创建一个缓存类,用于缓存数据库中的数据: ```java @Component public class DataCache { private Map<Long, Object> cache = new HashMap<>(); public void put(Long id, Object data) { cache.put(id, data); } public Object get(Long id) { return cache.get(id); } public Map<Long, Object> getAll() { return Collections.unmodifiableMap(cache); } } ``` 2. 创建一个数据加载类,实现ApplicationRunner或CommandLineRunner接口,并在其实现的run方法中将数据库中的数据缓存至Map中: ```java @Component public class DataLoadRunner implements ApplicationRunner { @Autowired private DataCache dataCache; @Autowired private DataSource dataSource; @Override public void run(ApplicationArguments args) throws Exception { try (Connection conn = dataSource.getConnection()) { String sql = "SELECT id, data FROM table"; try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { while (rs.next()) { Long id = rs.getLong("id"); Object data = rs.getObject("data"); dataCache.put(id, data); } } } } } ``` 在这个例子中,我们使用了Spring Boot提供的DataSource来获取数据库连接,然后使用JDBC API将数据从数据库中查询出来,并存储至DataCache中。 3. 在Spring Boot启动类中添加注解@EnableScheduling,开启定时任务功能,以便在数据发生变化时,能够及时更新缓存。 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,在Spring Boot项目启动完成后,数据就会被缓存至Map中,并可以通过DataCache在整个应用程序中访问。如果数据发生变化,可以通过定时任务重新加载数据到缓存中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值