Reputation: 14286
In JAX-RS we can inject @Context
instances like HttpServletRequest
as a class field or as a method parameter.
Are there any differences between those two options?
I belive Singletons will have some sort of proxy injected instead, but are there any side-effects to be aware of? Or are they transparent and it's just a matter of personal taste?
Upvotes: 1
Views: 1023
Reputation: 11
@Inject and @context have different targets. @Inject cannot be used for params and @context cannot be used in constructors. A very popular use case for @context is indeed in param position.
The majority of JAX-RS resource methods use @context in param position, except for the entity. This would need to be converted to an @Inject at method level, but would make things less clear regarding the entity param. There's also the issue of ContextResolver's which are somewhat similar to CDI producers and would need tweaking.
We can check Java doc:
@Context: @Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Inject: @Target({ METHOD, CONSTRUCTOR, FIELD })
Upvotes: 0
Reputation: 1283
For the most part, it is simply personal preference.
My advice would be to inject as class fields, as the @Context
annotation will eventually be replaced by @Inject
from CDI - and the @Inject
annotation does not target method parameters. You can read more of the discussion here.
Upvotes: 2