我正在尝试学习如何创建RESTful Web服务。 我正在尝试执行以下操作: 创建一个从消息列表返回消息对象(JSON格式)的方法。 (已使用构造函数初始化)
它正常运行这些URI:
http://localhost:8080/MyMessenger/webapi/testresource/1 http://localhost:8080/MyMessenger/webapi/testresource/2 http://localhost:8080/MyMessenger/webapi/testresource/3
对于URI: http://localhost:8080/MyMessenger/webapi/testresource/4
我收到以下回复:
{
"id": 1,
"message": "m1"
}
但是,我在arraylist中只添加了3个元素。 我在这里做错了什么?
我猜这与多次运行构造函数有关。但我不认为这发生在任何地方。
@Path("testresource")
public class MessageResource {
private static List<Message> list = new ArrayList<>();
public MessageResource() {
list.add(new Message(1L,"m1"));
list.add(new Message(2L,"m2"));
list.add(new Message(3L,"m3"));
}
@GET
@Path("{messageId}")
@Produces(MediaType.APPLICATION_JSON)
public Message getSpecificMessage(@PathParam("messageId") int messageId) {
return list.get(messageId-1);
}
}
答案 0 :(得分:2)
列表为static
。这意味着该类的所有实例只有一个列表实例。资源类在请求范围中是默认的,这意味着为每个请求实例化一个新资源。因此,每次创建新的时,它都会添加到相同的static
列表中。
如果您希望资源类是单例(只有一个),那么您可以使用@Singleton
对其进行注释。