在config文件夹中新建一个项目初始化类 InitConfig.java
代码如下
package com.example.demo.base.config;
import com.example.demo.love.entity.User;
import com.example.demo.love.mapper.UserMapper;
import com.example.demo.util.RedisUtil;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
/**
* 项目初始化类
* @author DaenMax
*/
@Configuration
public class InitConfig implements ApplicationRunner {
@Resource
private UserMapper userMapper;
@Resource
private RedisUtil redisUtil;
@Override
public void run(ApplicationArguments args) throws Exception {
//此处仅是举例
User user = userMapper.selectById("1");
redisUtil.set(String.valueOf(user.getId()),user);
User user1 = (User) redisUtil.get(String.valueOf(user.getId()));
System.out.println("项目初始化成功,读取结果为:" + user1.getId() + "," + user1.getName());
}
}
测试
然后按之前那样正常启动或者调试就好,运行结果如下