在微服务开发中为Spring Boot应用程序返回对象列表时出错

时间:2019-07-04 05:07:32

标签: java spring spring-boot collections microservices

  • 我按照youtube上的微服务教程创建了独立的服务(spring boot应用程序)
  • 我创建了一个服务实现Java文件,其中提供了用于读取操作的请求映射URL(/ catalog / userId)的方法定义
  • 对于上述请求的URL,返回对象列表作为HTTP读取请求的响应正文(HTTP响应)
  • 在Java中,发送对象列表的函数定义发生错误
  • MovieCatalogResource.java的第17行中发生错误,指出表达式的非法开头,意外的令牌
  • 我研究了错误,但仍然对执行感到震惊
  • 你们能否请您提供帮助,以解决您的建议问题
  • 提供以下代码

CatalogItem.java

package com.example.moviecatalogservice;

public class CatalogItem {
    private String name;
    private String desc;
    private int rating;
    public CatalogItem(String name, String desc, int rating){
        this.name = name;
        this.desc = desc;
        this.rating = rating;
    }
    public int getRating(){
        return rating;
    }
    public void setRating(){
        this.rating = rating;
    }
    public String getName(){
        return name;
    }
    public void setName(){
        this.name = name;
    }
    public String getDesc(){
        return desc;
    }
    public void setDesc(){
        this.desc = desc;
    }
}

MovieCatalogService.java

package com.example.moviecatalogservice;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.an notation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/catalog")
public class MovieCatalogResource {
    @RequestMapping("/{userId}")
    //public List<CatalogItem> getCatalog(@PathVariable("userId") String userId){
    public List<CatalogItem> getCatalog(@PathVariable("userId") String userId){
        return Collections.singletonList(
                new CatalogItem(name: "transformers", desc:"Test", rating:4)
        );
    }

}

2 个答案:

答案 0 :(得分:1)

更改

new CatalogItem(name: "transformers", desc:"Test", rating:4)

收件人

new CatalogItem("transformers", "Test", 4)
  

在CatalogItem中必须具有匹配的CatalogItem()构造函数   实体或模型

change at line no 17的{​​{1}}之后,如下图所示

MovieCatalogResource.java

工作示例

Controller.java

@RestController
@RequestMapping("/catalog")
public class MovieCatalogResource {
    @RequestMapping("/{userId}")
    //public List<CatalogItem> getCatalog(@PathVariable("userId") String userId){
    public List<CatalogItem> getCatalog(@PathVariable("userId") String userId){
        return Collections.singletonList(
                new CatalogItem("transformers", "Test", 4)
        );
    }

}

User.java

@GetMapping("/{id}")
    public List<User> getUser(@PathVariable(name="id") int id)
    {
        return Collections.singletonList(
                new User(1,"username")
        );
    }

使用邮递员测试 enter image description here

答案 1 :(得分:1)

您为什么这样做:

new CatalogItem(name: "transformers", desc:"Test", rating:4)

代替此:

new CatalogItem("transformers", "Test", 4)

MovieCatalogResource.java的第17行?