Spring NullPointerException this.service 为 null

Spring NullPointerException this.service is null

提问人:huga721 提问时间:11/24/2022 更新时间:11/24/2022 访问量:483

问:

我的 NullPointerException 有问题,/register 端点上的每个 POST,NullPointerException 显示服务是带有 /register 的
null 控制器

@AllArgsConstructor
@RestController
@Validated
public class SecurityController {

    private final UserService service;

    @PostMapping("/register")
    private ResponseEntity<UserDTO> registerUser (@RequestBody @Valid RegisterDTO registerDTO) {
        return ResponseEntity.created(URI.create("/user")).body(service.createUser(registerDTO));
    }

用户服务

@RequiredArgsConstructor
@Service
public class UserService implements UserServiceApi {
    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    private final PasswordEncoder encoder;

    @Override
    public UserDTO createUser(RegisterDTO user) {
        if (user.equals(userRepository.findByUsername(user.getUsername()))) {
            throw new RuntimeException("This nickname is already taken");
        }
        if (user.equals(userRepository.findByEmail(user.getEmail()))) {
            throw new RuntimeException("This email is already taken");
        }
        // Encoding password
        user.setPassword(encoder.encode(user.getPassword()));
        // On creating new Account it's going to have USER role
        Role role = roleRepository.findByName("USER");

        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();

        User dto = buildUser(username, password, email, role);

        userRepository.save(dto);
        return UserDTO.builder()
                .username(username)
                .password(password)
                .email(email)
                .build();
    }

其他使用服务的控制器,我不知道这可能是问题的线索

@RestController(value = "/user")
@AllArgsConstructor
@Validated
public class UserController {
    private final UserService service;

    @GetMapping("/getusers")
    public ResponseEntity<List<User>> getAllUser() {
        return ResponseEntity.ok(service.getUsers());
    }
Java Spring 服务 控制器 NullPointerException

评论

0赞 Stultuske 11/24/2022
您是否尝试过自动布线该服务?
0赞 Teddy Tsai 11/24/2022
您能告诉我们您是如何注入服务的吗?
2赞 M. Deinum 11/24/2022
从控制器中删除,然后使方法 . 在类级别上,它有不同的用途,在这里不需要。导致创建代理,因为您的方法会导致在代理上调用方法,而不是将其传递给实际对象。代理没有设置任何内容,因此 .根据经验法则,无论如何,您的控制器方法都应该如此。@Validatedpublic@ValidatedprivateNullPointerExceptionpublic
0赞 huga721 11/24/2022
@M.Deinum制作公开方法有效,很高兴了解,谢谢@Validated
0赞 huga721 11/24/2022
@TeddyTsai据我所知,我向龙目岛注入了服务@AllArgsConstructor

答: 暂无答案