Ошибка
WARN 12316 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Invocation of init method failed; nested exception is java.lang.NullPointerException
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Invocation of init method failed; nested exception is java.lang.NullPointerException
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@PostConstruct
public void unit() {
User user = userRepository.findByUsername("admin");
if (user == null) {
Role role = roleRepository.findByName("admin");
if (role == null) {
role.setName("ADMIN"); // Дебагером здесь получаю NullPointerException
roleRepository.save(role);
}
user.setUsername("admin");
user.setPassword(new BCryptPasswordEncoder().encode("admin"));
user.setRoles(new HashSet<>(roleRepository.findAll()));
userRepository.save(user);
}
}
Метод смотрит есть ли пользователь admin и если нет создает его. Не очень понимаю из за чего ошибка.