0

I'm trying to save user data send via rest controller to database using a service and a repository.

Controller

@RestController
@RequestMapping(path="/users")
public class UserController {

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(method= RequestMethod.POST, path="/create" )
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public void createUser(@RequestBody @Validated UserDto userDto ){

        userService.createUser(userDto.getUsername(), userDto.getEmail(), userDto.getPassword());

    }
}

Service

@Service
public class UserService {

    private UserRepository userRepository;
    private BCryptPasswordEncoder encoder;

    @Autowired
    public UserService(UserRepository userRepository){
        this.userRepository = userRepository;
    }

    public void createUser(String username, String email,String password){

        userRepository.save(new User(username, email, encoder.encode(password))); //line 25
    }

    public Optional<User> getByUsername(String username){
        return userRepository.findByusername(username);
    }
}

Repository

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
    Optional<User> findByusername(String username);
}

I'm sending a POST request to this http://localhost:8080/users/create url with below data

{
  "username": "testusername",
  "password": "password123",
  "passwordRepeat": "password123",
  "email": "asd@gm.com",
  "emailRepeat": "asd@gm.com"
}

Here is the exception i get when i do so,

java.lang.NullPointerException: null
    at com.mportal.ec.services.UserService.createUser(UserService.java:25)
    at com.mportal.ec.web.UserController.createUser(UserController.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

I can't figure out the reason here. please help.

Harsha Jayamanna
  • 2,148
  • 6
  • 25
  • 43

1 Answers1

1

This isn't happening because you're accessing a repository, but because you're using encoder.encode() even though BCryptPasswordEncoder isn't autowired.

You have the following fields:

private UserRepository userRepository;
private BCryptPasswordEncoder encoder;

But you autowired only one:

@Autowired
public UserService(UserRepository userRepository){
    this.userRepository = userRepository;
}

So, you can fix it by changing your constructor to:

@Autowired
public UserService(UserRepository userRepository, BCryptPasswordEncoder encoder) {
    this.userRepository = userRepository;
    this.encoder = encoder; // This line is missing
}

You need to have a BCryptPasswordEncoder bean available though.

g00glen00b
  • 41,995
  • 13
  • 95
  • 133