有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在API中返回单例列表?

我正在学习使用Eclipse IDE和Spring Boog框架创建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模式以显示要在浏览器上显示的catalogitem的硬编码值

我在以下行中遇到错误:

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

共 (3) 个答案

  1. # 1 楼答案

    我希望您的getCatalog方法中存在编译时错误。请更改退货声明,如下所示:

    public List<CatalogItem> getCatalog(@PathVariable("user_id") String user_id)
            {
                return Collections.singletonList(new CatalogItem("DonJon", "Test", 4));
            }
    
  2. # 2 楼答案

    AFAIK Java不支持命名参数。所以这条线

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

    将给出您面临的语法错误。换成

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

    它应该会起作用

  3. # 3 楼答案

    在月食中

    1. 点击Windows>;首选项,然后选择左侧的Maven
    2. 选中“启动时下载存储库索引更新”框。
      • 或者,选中下载工件源下载工件JavaDoc复选框
    3. 点击OK。警告将不再出现
    4. 重新启动Eclipse