首页 > 解决方案 > 使用 spring boot 使用 api

问题描述

我是 Spring 新手,我正在尝试使用通过使用 Student Repository 中的注释 @RestRepositoryResources 创建的 API,如下所示:

@RepositoryRestResource
public interface StudentRepository extends JpaRepository<Student, Long> {

}

所以,我想从另一个项目中使用 API,如下所示:

@RestController
public class StudentController {
    
    @Autowired
    private RestTemplate restTemplate;
    
    @GetMapping
    public List<Student> getStudents(){
        ListStudent response=restTemplate.getForObject("http://localhost:8080/student-service/students", ListStudent.class);
        System.out.println(response);
        return response.getStudents();
    }
}

当然这不起作用,因为响应的格式

{
     "_embedded": {
     "students": []
    },
    "_links": {
    "self": {
    "href": "http://localhost:8081/students"
    },
    "profile": {
    "href": "http://localhost:8081/profile/students"
    }
    },
       "page": {
        "size": 20,
        "totalElements": 0,
        "totalPages": 0,
        "number": 0
    }  
}

标签: javaspringspring-boot

解决方案


我不确定是什么ListStudent,但您的类需要匹配 JSON 响应,尽管它可以省略您不需要的任何内容。你需要一个StudentResponse类之类的东西,其中包含一个List<Student>.


推荐阅读