在项目启动的时候需要做一些初始化的操作,比如初始化线程池、提前加载mysql数据库到缓存等。Springboot中
CommandLineRunner
接口的 Component
会在所有 Spring Beans
都初始化之后SpringApplication.run()
之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作。
package com.xf.zhang.init; import com.xf.zhang.mapper.UserMapper; import com.xf.zhang.pojo.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.List; @Component public class MyStartupRunner implements CommandLineRunner { private Logger logger= LoggerFactory.getLogger(MyStartListener.class); @Resource private RedisTemplate redisTemplate; @Resource private UserMapper userMapper; @Override public void run(String... strings) throws Exception { List<User> list= userMapper.selectAll(); list.forEach(action->{ redisTemplate.opsForZSet().add("userList",action,action.getId()); logger.info(action.toString()); }); } }