从Spring4中的服务访问存储库时出现NullPointerException

时间:2017-07-03 12:24:44

标签: java spring spring-boot repository

我尝试使用服务和存储库将通过其他控制器发送的用户数据保存到数据库。

控制器

@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
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
public interface UserRepository extends JpaRepository<User, Integer> {
    Optional<User> findByusername(String username);
}

我向此http://localhost:8080/users/create网址发送POST请求,其中包含以下数据

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

以下是我这样做的例外情况,

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)

我无法在这里找出原因。请帮忙。

1 个答案:

答案 0 :(得分:1)

这不会发生,因为您正在访问存储库,但是因为您使用的是encoder.encode(),即使BCryptPasswordEncoder未自动装配。

您有以下字段:

private UserRepository userRepository;
private BCryptPasswordEncoder encoder;

但是你只用了一个:

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

因此,您可以通过将构造函数更改为:

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

你需要有一个BCryptPasswordEncoder bean。