gpt4 book ai didi

java - Spring4中从Service访问Repository时出现NullPointerException

转载 作者:行者123 更新时间:2023-12-02 12:42:30 25 4
gpt4 key购买 nike

我正在尝试使用服务和存储库将通过休息 Controller 发送的用户数据保存到数据库。

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
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)

我无法弄清楚这里的原因。请帮忙。

最佳答案

发生这种情况并不是因为您正在访问存储库,而是因为您正在使用 encoder.encode(),即使 BCryptPasswordEncoder 未 Autowiring 。

您有以下字段:

private UserRepository userRepository;
private BCryptPasswordEncoder encoder;

但是您只 Autowiring 了一个:

@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。

关于java - Spring4中从Service访问Repository时出现NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44885539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com