首页 > 解决方案 > 如何在 API 中返回单例列表?

问题描述

我正在学习使用 Eclipse IDE 和 Spring-Boot 框架创建 Java API。因此,我面临着一个我无法解决的语法问题。以下是我的代码供您参考:

package first.microservice.moviecatalogservice.resources;

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

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import first.microservice.moviecatalogservice.models.CatalogItem;

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

另一个具有 CatalogItem 类的代码:

package first.microservice.moviecatalogservice.models;

public class CatalogItem {

    private String Name;
    private String Desc;
    private int Rating;
    
    public CatalogItem(String name, String desc, int rating) {
        Name = name;
        Desc = desc;
        Rating = rating;
    }
    
    public String getName() {
        return Name;
    }
    public void setName(String name) {
        Name = name;
    }
    public String getDesc() {
        return Desc;
    }
    public void setDesc(String desc) {
        Desc = desc;
    }
    public int getRating() {
        return Rating;
    }
    public void setRating(int rating) {
        Rating = rating;
    }
    
    
}

我希望输入 URL 模式以显示要在浏览器上显示的目录项的硬编码值。

我在以下行中遇到错误:

return Collections.singletonList(
                     <CatalogItem> new CatalogItem(name: "DonJon", desc: "Test", rating: 4)
                    );

该错误指出:

The method singletonList(T) in the type Collections is not applicable for the arguments (CatalogItem)

Multiple markers at this line
    - Syntax error on token "<", invalid Expression
    - Syntax error on token ":", invalid     AssignmentOperator
    - name cannot be resolved to a variable
    - Syntax error on token ":", invalid     AssignmentOperator
    - desc cannot be resolved to a variable
    - Syntax error on token ":", invalid     AssignmentOperator
    - rating cannot be resolved to a variable

标签: javaapispring-boot

解决方案


AFAIK Java 不支持命名参数。因此,这条线

<CatalogItem> new CatalogItem(name: "DonJon", desc: "Test", rating: 4)

将给出您面临的语法错误。改变它

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

它应该工作


推荐阅读