【发布时间】:2021-01-18 20:39:42
【问题描述】:
我有一个 Spring Boot 应用程序,其中自动装配的服务突然在特定方法返回 null。
这是控制器的代码 sn-p:
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserManagementController {
@Autowired
private UserService userService;
...
@PostMapping("/register")
private GameInfo register(@RequestBody UserInfo userInfo) {
User user = new User();
...
user.setUsername("user-" + userService.count());
...
return gameController.getGameInfo(user);
}
...
@PostMapping("/statistics")
public StatisticsInfo statistics(
@RequestParam(name = "username", required = true) String username,
Authentication authentication) {
User user = userService.findByUsername(username);
...
}
}
userService 在第一种方法中为空,在第二种方法中工作正常。
更新: 这是 UserService 的代码 sn-p,在“注册”方法中为 null。
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepository repository;
public long count() {
return repository.count();
}
...
}
userService 具有正常的 CRUD 方法。
请注意,userService 为 null,因此当我调用它的任何方法时都会引发 NullPointerException。
更新 2:
我已经创建了错误方法register的克隆并将其命名为dontRegister,这神奇地解决了register的问题,但在新方法中引入了同样的问题。
我不明白这背后的逻辑,因为我似乎总是需要添加一个额外的未使用的方法。
我会一直保持这个问题,直到有人提出解释为止。
【问题讨论】:
-
你确定第二个方法没有在子类中被覆盖吗? (即您确定该代码实际运行吗?)
-
很遗憾,是的。在我感到沮丧并在这里发布问题之前,我对其进行了多次审查并在邮递员中对其进行了测试。此外,此控制器没有子类
-
“返回空值”是什么意思?来自 count() 方法?
-
您没有包含构造函数或可以在代码中设置字段的任何其他位置。是否有可能在字段初始化之前调用第二个方法?
-
@daniu "userService" 本身为空,而不是 count() 方法。
标签: java spring spring-boot