package com.mobizone.kb.config;
import com.mobizone.kb.entity.Users;
import com.mobizone.kb.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class DataInitializerConfig implements CommandLineRunner {
@Autowired
private IUsersService usersService;
@Override
public void run(String... args) throws Exception {
// 检查是否存在admin用户
if (usersService.userExists("admin") == false) {
Users admin = new Users();
admin.setUsername("admin");
// 加密密码
admin.setPassword("123456");
usersService.addUser(admin);
System.out.println("管理员账号创建成功");
}
}
}
CommandLineRunner是Spring Boot提供的一个接口,用于在应用程序完全启动后执行特定的代码逻辑。
CommandLineRunner的作用
1. 启动后执行
在Spring Boot应用完全启动后自动执行
所有Bean都已初始化完成
可以安全地访问数据库和其他服务
2. 初始化数据
常用于项目启动时的数据初始化
创建默认用户、角色等基础数据
数据库预填充
执行时机
启动顺序:
Spring容器启动
所有Bean创建和初始化
应用上下文完全准备就绪
CommandLineRunner.run()方法执行 ← 这里
应用可以接收请求