javaspring-bootspring-mvc

How to preload common resource in a Spring Boot RestController?


I have a Controller with RequestMapping(foo/{fooId}/bar/}), FooEntity is used in all methods, how can i preload FooEntity for all the methods of FooController?

@RestController
@RequestMapping("foo/{fooId}/bar")
public class FooController {

  public void prefetchFoo(@PathVariable Long fooId) {
   ...
  }
  
  @PostMapping("/")
  public ResponseEntity<void> createFooBar(FooEntity prefetchedFoo) {
   ...
  }

 
  @GetMapping("/{barId}")
  public ResponseEntity<void> getFooBar(FooEntity prefetchedFoo) {
   ...
  }

}

I have found @ModelAttribute in my research, but i only saw it in the context of web views, is it viable to use it in the context of JSON APIs?


Solution

  • You can use @ModelAttribute in the context of JSON APIs. The @ModelAttribute method will be called before each request handler method and can populate the model attribute with the necessary data. This is applicable regardless of whether your API produces views or JSON responses.

    @RestController
    @RequestMapping("foo/{fooId}/bar")
    public class FooController {
    @Autowired
    private FooService fooService;
    
    @ModelAttribute
    public FooEntity prefetchFoo(@PathVariable Long fooId) {
        // Logic to fetch FooEntity based on fooId
        return fooService.findFooById(fooId);
    }
    
    @PostMapping("/")
    public ResponseEntity<Void> createFooBar(@ModelAttribute FooEntity prefetchedFoo) {
        ...
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/{barId}")
    public ResponseEntity<FooEntity> getFooBar(@PathVariable Long barId, @ModelAttribute FooEntity prefetchedFoo) {
       ...
        return ResponseEntity.ok(prefetchedFoo);
    }
    }