[英]AutoWired JPA Repository is null in some method of controller
I have a JPARepository like this我有一个这样的 JPARepository
@Repository
public interface RestaurantRepo extends JpaRepository<Restaurant, String> {
Optional<Restaurant> findByName(String name);
Optional<List<Restaurant>> findAllByMerchantId(String merchantId);
}
I then have a controller where I am initializing the Repository like this然后我有一个控制器,我正在像这样初始化存储库
@Autowired
RestaurantRepo restaurantRepo;
Then I have one method where I am using the Repository like this然后我有一种方法可以像这样使用存储库
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@GetMapping("/disable")
public ResponseEntity<CustomResponse> disableUser(String username, boolean disable) {
Restaurant restaurant = restaurantRepo.findById(username).get();
restaurant.setDisabled(disable);
CustomResponse er = new CustomResponse();
er.setStatus("Successful");
if (disable) {
er.setMessage("Restaurant is disabled");
} else {
er.setMessage("Restaurant is enabled");
}
restaurantRepo.save(restaurant);
return new ResponseEntity<>(er, new HttpHeaders(), HttpStatus.OK);
}
Whenever I hit this api, it works fine.每当我点击这个 api 时,它都可以正常工作。 Then I have another method like this
然后我有另一个这样的方法
@PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN','ROLE_RESTAURANT')")
@GetMapping("/get")
private ResponseEntity<Restaurant> getRestaurant(Principal principal) {
String username = principal.getName();
System.out.println("username "+username); //prints the valid username
System.out.println("RestRepo "+restaurantRepo); //prints null
Restaurant restaurant;
Optional<Restaurant> opt = restaurantRepo.findById(username); //prints Exception here
if (opt.isPresent()) {
restaurant = opt.get();
return new ResponseEntity<>(restaurant, HttpStatus.OK);
} else {
restaurant = new Restaurant();
return new ResponseEntity<>(restaurant, HttpStatus.NOT_FOUND);
}
}
Here I get a NullPointerException in this line Optional<Restaurant> opt = restaurantRepo.findById(username);
在这里,我在这一行中得到 NullPointerException
Optional<Restaurant> opt = restaurantRepo.findById(username);
The username is a valid username, and so when I print the restaurantRepo
I get null
.用户名是一个有效的用户名,所以当我打印
restaurantRepo
我得到null
。
I am confused as to why the variable is not null in one method while it is null in another method.我很困惑为什么变量在一种方法中不为空而在另一种方法中为空。 Any help would be appreciated.
任何帮助,将不胜感激。 Thanks
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.