简体   繁体   中英

How can i use a RestControler function in another RestControler

I get org.springframework.beans.factory.UnsatisfiedDependencyException when i call SaleRestService in ProductRestService like in the code below.

How can i do it properly?

@RestController
@CrossOrigin("*")
public class ProductRestService {
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    public SaleRestService saleRestService ; 

    @RequestMapping(value="/productQuatityMinusOne", method=RequestMethod.GET)
    @ResponseBody
    public void ProductQuatityMinusOne(@RequestParam(name="id") Long id){
        Product p = productRepository.findProductById(id);
        double salePrice = p.getPrice();
        Date now = new java.util.Date();
        Sale s = new Sale(id,salePrice,now);
        saleRestService .saveOneSale(s);
        p.setId(id);
        int q = p.getQuantity()-1;
        p.setQuantity(q);
        productRepository.save(p);
    }
}

@RestController
@CrossOrigin("*")
public class SaleRestService {

    @Autowired
    private SaleRepository saleRepository; 

    //Save one sale
    @RequestMapping(value="/saveOneSale", method=RequestMethod.POST)
    @ResponseBody
    public Sale saveOneSale(@RequestBody Sale s){
         return saleRepository.save(s);
    }
}

You should not be calling your controllers from one another.

Two solutions:

  • Put the code of the saveOneSale in another @Service, and call that from your @RestControllers
  • You could redirect the http call of ProductQuatityMinusOne in ProductRestService to saveOneSale in SaleRestService by using a spring boot redirect, like this return "redirect:/saveOneSale"; , but I dont know if that will work because you'd be redirecting to a POST handler.

Personlly I'd do the first solution:

  • remove @RestController from SaleRestService
  • create a SaleRestController class, anotate it with @RestController, and put a method with the following annotation: @RequestMapping(value="/saveOneSale", method=RequestMethod.POST)
  • in that method, call SaleRestService.saveOneSale

Everything should just work (TM)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM