Spring Data REST: Override repository method on the controller

后端 未结 4 819
暖寄归人
暖寄归人 2020-12-05 10:32

I have the following REST repository, whose implementation is generated at runtime by Spring.

@RepositoryRestResource
public interface FooRepository extends          


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 10:57

    Is there a way of overriding REST methods while still keeping the other auto-generated Spring methods?

    Look at the example in the documentation carefully: while not explicitly forbidding class-level requestmapping, it uses method-level requestmapping. I'm not sure if this is the wanted behavior or a bug, but as far as I know this is the only way to make it work, as stated here.

    Just change your controller to:

    @RepositoryRestController
    public class FooController {
    
        @Autowired
        FooService fooService;
    
        @RequestMapping(value = "/foo/{fooId}", method = RequestMethod.PUT)
        public void updateFoo(@PathVariable Long fooId) {
            fooService.updateProperly(fooId);
        }
    
        // edited after Sergey's comment
        @RequestMapping(value = "/foo/{fooId}", method = RequestMethod.PUT)
        public RequestEntity updateFoo(@PathVariable Long fooId) {
            fooService.updateProperly(fooId);
    
            return ResponseEntity.ok().build(); // simplest use of a ResponseEntity
        }
    }
    

提交回复
热议问题