【问题标题】:AutoWired JPA Repository is null in some method of controllerAutoWired JPA Repository 在控制器的某些方法中为空
【发布时间】:2020-11-08 06:54:56
【问题描述】:

我有一个这样的 JPARepository

@Repository
public interface RestaurantRepo extends JpaRepository<Restaurant, String> {
    Optional<Restaurant> findByName(String name);

    Optional<List<Restaurant>> findAllByMerchantId(String merchantId);
}

然后我有一个控制器,我正在像这样初始化存储库

@Autowired
RestaurantRepo restaurantRepo;

然后我有一种方法可以像这样使用存储库

@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);
    }

每当我点击这个 api 时,它都能正常工作。 然后我有另一种这样的方法

@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);
        }

    }

在这里,我在这一行 Optional&lt;Restaurant&gt; opt = restaurantRepo.findById(username); 得到一个 NullPointerException

用户名是有效的用户名,所以当我打印restaurantRepo 时,我得到null

我很困惑为什么变量在一种方法中不为空,而在另一种方法中为空。任何帮助,将不胜感激。谢谢

【问题讨论】:

  • disableUser 和 getRestaurant 方法是否在同一个控制器中?
  • @Niyas 是的,它们在同一个控制器中

标签: java spring spring-boot spring-mvc spring-data-jpa


【解决方案1】:

我不确定。但是尝试将第二种方法中的访问修饰符更改为public
请参考这个thread

也使用构造函数注入代替@Autowired注解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多