java - Spring 数据 REST : Override repository method on the controller

标签 java spring rest spring-data-rest

我有以下 REST 存储库,其实现由 Spring 在运行时生成。

@RepositoryRestResource
public interface FooRepository extends CrudRepository<Foo, Long> {

}

这意味着我将拥有 save()、find()、exists() 和其他可用并通过 REST 公开的方法。

现在,我想重写其中一种方法;例如,保存()。为此,我将创建一个公开该方法的 Controller ,如下所示:

@RepositoryRestController
@RequestMapping("/foo")
public class FooController {

    @Autowired
    FooService fooService;


    @RequestMapping(value = "/{fooId}", method = RequestMethod.PUT)
    public void updateFoo(@PathVariable Long fooId) {
        fooService.updateProperly(fooId);
    }

}

问题: 如果我启用这个 Controller ,那么 Spring 实现的所有其他方法都不再暴露。因此,例如,我不能再向/foo/1 发出 GET 请求

问题: 有没有一种方法可以覆盖 REST 方法,同时仍保留其他自动生成的 Spring 方法?

额外信息:

  1. 这个问题看起来很相似: Spring Data Rest: Override Method in RestController with same request-mapping-path ...但我不想将路径更改为/foo/1/save

  2. 我曾想过使用@RepositoryEventHandler,但我不太喜欢这个想法,因为我想将它封装在一个服务下。此外,您似乎失去了对事务上下文的控制。

  3. This part of the Spring Data documentation说如下:

    Sometimes you may want to write a custom handler for a specific resource. To take advantage of Spring Data REST’s settings, message converters, exception handling, and more, use the @RepositoryRestController annotation instead of a standard Spring MVC @Controller or @RestController

所以它似乎应该开箱即用,但不幸的是不是。

最佳答案

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

仔细查看文档中的示例:虽然没有明确禁止类级别的请求映射,但它使用了方法级别的请求映射。 我不确定这是想要的行为还是错误,但据我所知,这是使其工作的唯一方法,如 here 所述.

只需将您的 Controller 更改为:

@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<Void> updateFoo(@PathVariable Long fooId) {
        fooService.updateProperly(fooId);

        return ResponseEntity.ok().build(); // simplest use of a ResponseEntity
    }
}

关于java - Spring 数据 REST : Override repository method on the controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36773171/

相关文章:

java - 获取 'Mobile network' 的状态,wifi 断开后自动连接 3g 的状态

java - 无法获取 Derby 10.15 的驱动程序实例

JavaFX - 访问动态创建的选项卡 Controller

java - 如何在应用程序启动期间处理 org.hibernate.exception.GenericJDBCException?

api - REST API : Where should I code my workflow?

java - 如何对这两个耦合类应用解耦

java - 两个不同的 URI 映射相同的 View ,一个工作正常,但另一个无法加载 css

java - 通用 Spring Data JPA 存储库 findAll

c# - C# 中 REST 端点上的 SSL?

rest - 带有身份验证的 REST API 中的 CSRF token