java - 在 REST API 中实现子资源

标签 java rest design-patterns

我需要在 REST API 中实现子资源

网址将类似于:
https://localhost:8080/v1/student/ {id}?include=地址、资格、登录

所以地址、资格和登录是三个子资源,如果我们添加这是查询参数,则会包含这些子资源。子资源可以是数据库调用或对其他服务的其余调用

问题发生在实现方面,我已采用@RequestParam List include

所以目前我在服务类中这样写

 public Student getStudentDetail(Integer id ,List<String> include){
    Student student = new Student();
    // setting student details
    for(String itr: include){
    if(itr=="address"){
    student.setAddress(repo.getAddress(id));
    }
    if(itr=="qualification"){
    student.setQualication(repo.getQualification(id));
    }
    if(itr=="login"){
    student.setLogin(client.getLogin(id));// here client in Rest Call for 
    }


   }
    return student;
    }

学生类(class):

@Data
public Class Student{
private String id;

private List<Address> address;

private List<Qualification> qualification;

private Login login; 
}

所以在这里我需要为每个子资源添加 if 条件,您能否建议任何更好的方法或任何设计原则。

还有另一种方法可以使用反射 API 在运行时获取存储库方法名称,但它会增加额外的调用开销。

另一种方法可以是:

我可以使用策略设计模式

Abstract Class 

public Abstract class Subresource{
public Student getSubresouce(Integer id,Student student){}
}

public class Address extends Subresource{
@Autowired
Databaserepo repo;

public Student getSubresource(Integer id , Student student){
  return student.setAddress(repo.getAddress(id));
}
}

public class Login extends Subresource{
@Autowired
RestClient client;

public Student getSubresource(Integer id, Student student){
 return student.setLogin(client.getLogin(id));
}
}

但在这种方法中我无法在服务中编写逻辑

  public Student getStudentDetail(Integer id ,List<String> include){
        Student student = new Student();
        // setting student details
        for(String itr: include){
       // Need to fill logic
// Help me here to define logic to use strategy oattern
       }
        return student;
        }

最佳答案

您正在寻找的是投影。从这里link

Projections are a way for a client to request only specific fields from an object instead of the entire object. Using projections when you only need a few fields from an object is a good way to self-document your code, reduce payload of responses, and even allow the server to relax an otherwise time consuming computation or IO operation.

如果您使用 Spring here是一些例子。

关于java - 在 REST API 中实现子资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55250598/

相关文章:

java - NotSslRecordException : not an SSL/TLS record

java - 这是使用验证功能扩展所有 Java Swing GUI 的正确方法吗

java - 使用 Java http 客户端使用 Sharepoint 2010 REST API 发布数据

python - 测试 REST API

rest - 识别幂等操作冲突的最佳 Http 代码是什么

java - 抵消单纯形噪声返回值

java - 无法启动新项目eclipse

c# - 依赖注入(inject)模式下设计的基本原则是什么

c# - 使用存储库模式但没有工作单元构建单页应用程序 - 在哪里保存更改?

design-patterns - 为此设计模式?