Infinite Loop in REST API
Infinite Loop in REST API
Problem: The following code is making an infinite loop when calling /products/{id}. Why?
@RestController
@RequestMapping("/products")
public class ProductController {
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return getProduct(id);
}
}
The issue in the Infinite Loop in REST API question is that the method is calling itself recursively without a base case, causing a StackOverflowError due to infinite recursion.
Problematic Code:
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return getProduct(id); // Recursive call without exit condition
}
Instead of recursively calling getProduct(id), the method should fetch the product from a service or repository.
@Autowired
private ProductService productService;
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return productService.getProductById(id);
}
And the ProductService should look something like this:
@Service
public class ProductService {
public Product getProductById(Long id) {
// Fetch product from database or mock data
return new Product(id, "Sample Product");
}
}
- Key Takeaways:
- Recursive calls without an exit condition cause infinite loops and StackOverflowErrors.
- Always ensure REST controllers delegate logic to a service instead of self-calling methods.
- Base cases are required for recursion to terminate correctly.
Comments
Post a Comment