NullPointerException in @Service class

Viewed 12

The code below shows saving a user to a db in two different ways.

The first one is directly in the addUser method of the @RestController class.

The second one is in the addUser2 method in the @RestController class which calls @Service class.

The first one works fine, but the second one is throwing a nullpointerexception.

If you compare the two you will notice that both execute the same code. The only difference is that I moved the saving to the UserService class. But that method has the exact same code of the addUser method of Controller class that works fine.

The @RequestBody userDTO in all cases is null. I'm sending just {} in Postman. But still, it does work creating a new user when the save is done in the controller class, but it doesn't work in the Service class.

Why is that?

@RestController
public class UserController {   
    
    @Autowired
    private UserRepository userRepository;  

    @PostMapping(value = "/api/v1/user", produces = "application/json")
    public ResponseEntity<UserDTO> addUser(@RequestBody UserDTO userDTO){       
        
        User user = UserMapper.toUser(userDTO); 
        User addedUser = userRepository.save(user);
        UserDTO addedUserDTO = UserMapper.toUserDTO(addedUser);     
        
        return new ResponseEntity<UserDTO>(addedUserDTO, HttpStatus.OK);        
    }
    
    
    @PostMapping(value = "/api/v1/user2", produces = "application/json")
    public ResponseEntity<UserDTO> addUser2(@RequestBody UserDTO userDTO){
            
        UserService userService = new UserService();
        UserDTO addedUserDTO = userService.addUser(userDTO);
            
        return new ResponseEntity<UserDTO>(addedUserDTO, HttpStatus.OK);        
    }
}


@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;  
    
    public UserDTO addUser(UserDTO userDTO) {
        
        User user = UserMapper.toUser(userDTO);             
        User addedUser = userRepository.save(user);         
        UserDTO addedUserDTO = UserMapper.toUserDTO(addedUser);
        
        return addedUserDTO;        
    }
}
0 Answers
Related