Reputation: 2488
I know by default JAX-RS endpoints lifecycle is once-per-request, so that the request specific informations can be injected into the instance.
And we can also make an endpoints Singleton meaning once-per-application, in which the request specific informations cannot be injected into the instance rather it can be injected into the requested method.
1. So i would like to know which approach is better in terms of performance, either once-per-request or once-per-application.
2. I would also like to know the pros and cons of these approaches other the injecting request specific informations
3. Which approach you prefer to use in your API applications
Note: i have been using the once-per-request approach so far, but i always wonder is that is efficient, definitely its make coding easier and reusable.
Upvotes: 6
Views: 1744
Reputation: 10961
To start with your last question: I'm always using the default (per-request) and I seldom came to a point where I wanted to change this.
What might be a reason to prefer one over the other?
@ApplicationScoped
CDI bean in a per-request scoped resource class.@xxxParam
values like @QueryParam
as fields instead of method parameters you should use the per-request lifecycle. This is not supported for singletons. (This does not include injecting via @Context
).I made a little test to compare the performance of both. You can find the sources and the results on github. In short: I measured a difference from about 1.5 %. I don't think this should affect your application too much. Comparing the results of the JVisualVM monitoring I would tend to say that the per-request test is using more memory but you should decide on your own if this really affects your application.
Upvotes: 10