Mistake

WARN 12316 --- [restartedMain] ationConfigEmbeddedWebApplicationContext: Exception encountered during context initialization - canceling refreshing: org.springframework.beans.factory.BeanCreationException: Error: 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); } } 

The method looks if there is an admin user and if not, creates it. I do not really understand why an error.

    1 answer 1

    Spring can not initialize the context, because cannot create a bean named userServiceImpl . But it cannot create it because an exception is raised in the method declared by @PostContructor .

    You have an error in the following condition:

     Role role = roleRepository.findByName("admin"); if (role == null) { role.setName("ADMIN"); // Дебагером здесь получаю NullPointerException roleRepository.save(role); } 

    Those. role is checked for null and then the name is changed to a null reference. This naturally results in a NullPointerException