java - 将自定义方法添加到 Spring RepositoryRestResource

标签 java spring spring-data-rest

是否可以将自定义方法添加到 Spring @RepositoryRestResource 并将它们公开为 HTTP 端点,如下面的示例尝试(但失败)那样?或者我必须将自定义方法放在单独的 @Controller 中吗?

@RepositoryRestResource(path="person")
public interface PersonRepository extends CrudRepository<Person,Long> {

    // This works, as it's an integral part of what RepositoryRestResource does:
    // curl localhost:8080/person/search/findByNameStartsWith?prefix=MA
    Iterable<Person> findByNameStartsWith(@Param("prefix") String prefix);

    // This doesn't work:
    // curl -X POST -v localhost:8080/person/3/sendWelcomeLetter
    @RequestMapping(path = "/{id}/sendWelcomeLetter", method = RequestMethod.POST)
    default String sendWelcomeLetter(@PathVariable("id") Long id) {
        return "This is a custom method that would generate and send a letter.";
    }
}

最佳答案

sendWelcomeLetter 不是 ReST。 ReST中的ST意思是“状态转移”,你的调用是动态的,没有状态转移。

一个最小的解决方案可能是添加一个新的可为空的列“sent_welcome_newsletter”。

  • null 表示欢迎新闻通讯尚未发送。
  • false 表示无法发送欢迎简讯(收件箱已满或电子邮件无效)。
  • true 表示欢迎简讯过去已成功发送。

但是:请注意 legal right不被 DNSBL 阻止。如果不尊重这一标准,您的公司将陷入巨大的法律问题,并可能导致您失业!!!!

关于java - 将自定义方法添加到 Spring RepositoryRestResource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332584/

相关文章:

java - Spring MVC Controller 中的JSON参数

spring-data-rest - Spring Data Rest Jpa插入@Lob字段

Spring Boot Data Rest POST 返回 204 但只有 SELECTS

java - java中main()方法处理垃圾收集的方式是否不同

java - 为什么编译器不生成重复错误?

java - 关于 null 的 Comparable 和 Comparator 契约(Contract)

Java - 使用 FileOutputStream append 到 Excel 文件

java - 初始化数组,其中字段注入(inject)@Resource

java - Spring Kafka Streams - 创建流与注入(inject)现有的流 bean

Spring Data Rest - 按多个属性排序