java - 如何在 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
解决方案
AFAIK Java 不支持命名参数。因此,这条线
<CatalogItem> new CatalogItem(name: "DonJon", desc: "Test", rating: 4)
将给出您面临的语法错误。改变它
new CatalogItem("DonJon", "Test", 4)
它应该工作
推荐阅读
- solr - Solr 和 TYPO3 刻面
- reactjs - redux 工具包中的 reducer 和 extrareducers 有什么区别?
- r - 如何将 cat 结果保存为 data.frame
- reactjs - Building page with asynchronous react component does not render the latest iteration when building the documentation
- javascript - nwjs - 在二进制文件上调用函数
- vim - 如何删除 Neovim 上的插入符号
- python - 在执行 self.error_handler.check_response(response) 时我的代码
- java - Spring表单输入导致500服务器错误
- mysql - 为什么使用 MYSQL_PWD 被认为是不安全的?我认为环境变量是私有的,不像命令行参数
- spring-batch - 带有 MongoDB 和事务的 Spring 批处理