/
NikolayVasiljev
/
Project
Обзор
Документация
Войти
/
NikolayVasiljev
/
Project
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
feature
src/main/java/org/example/notesystem/config/DataInitializer.java
53 строки
2 KB
VasiljevNik
My first commit
02 авг 2025, 18:47
02 авг 2025, 18:47
9929e3e
Код
Авторство
О чём код?
package org.example.notesystem.config; import org.example.notesystem.model.Role; import org.example.notesystem.model.User; import org.example.notesystem.repository.RoleRepository; import org.example.notesystem.repository.UserRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.Set; @Configuration public class DataInitializer { @Bean CommandLineRunner initRoles(RoleRepository roleRepository) { return args -> { if (roleRepository.findByName("ROLE_USER") == null) { Role userRole = new Role(); userRole.setName("ROLE_USER"); roleRepository.save(userRole); } if (roleRepository.findByName("ROLE_ADMIN") == null) { Role adminRole = new Role(); adminRole.setName("ROLE_ADMIN"); roleRepository.save(adminRole); } }; } @Bean CommandLineRunner initUser(UserRepository userRepository, RoleRepository roleRepository) { return args -> { if (userRepository.findByUsername("Nikolay") == null) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); Role adminRole = roleRepository.findByName("ROLE_ADMIN"); if (adminRole == null) { adminRole = new Role(); adminRole.setName("ROLE_ADMIN"); roleRepository.save(adminRole); } User nikolay = new User(); nikolay.setUsername("Nikolay"); nikolay.setPassword(passwordEncoder.encode("123456")); nikolay.setRoles(Set.of(adminRole)); userRepository.save(nikolay); } }; } }