Reputation: 2741
I am learning how to implement Rest API through a tutorial project.
I am facing a rather strange behavior from a routine I perform in order to test the standard CRUD methods...
Here's a general description of the code architecture:
HashMap<Long, Message>
with Message
being the entity I am manipulating,
MessageService
which does the logic of the CRUD method implementations,MessageRessource
which is the Rest API containing all the @GET, @POST, etc...
method implementations which call the MessageService
instance methods.MessageService
constructor which I put in the database stub HashMap
Now, here's the routine which leaves me confused:
GET
on /messages
: Shows 2 entries,POST
with custom data: Data is added,GET
on /messages
: Shows 3 entries,DELETE
on /messages/3
: Deletes 3rd entry,GET
on /messages
: Shows 2 entries,DELETE
on /messages/2
: While debugging the app, the
messageService
instance in MessageRessource
has a hashmap of size 1 after the DELETE
method is processed,GET
on /messages
: Shows 2 entries instead of 1.My own thoughts on the problem:
GET
method in step 4 shouldn't show 3 entries but
only 2.DELETE
while the POST
does return the added data?For the code, please see the GitHub public project in the messenger App by AetosAkrivis
N.B : I know this isn't a real problem because I only need to remove the hardcoded Message
entries in the constructor in order to be able to perform normally. But I am really curious about the reason of the malfunctioning of this routine.
Upvotes: 1
Views: 76
Reputation: 39271
You have assumed that the JAX-RS container will only create one instance of the service MessageRessource
, but it can decide to clean instances or create multiple. Each time it is done the initialization, your static messages
will be updated with 2 additional entries. Results are indeterminate
@Path("/messages")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MessageRessource {
private MessageService messageService;
public MessageRessource() {
messageService = new MessageService();
}
public MessageService() {
messages.put(1L, new Message(1L,"Hi","Imad"));
messages.put(2L, new Message(2L,"Hello","Badr"));
}
P.S: Post your code instead of linking it
Upvotes: 1