Java Reference
In-Depth Information
The difference is that the
@Consumes
annotation is used instead of the
@Produces
annotation
to correlate media types.
Let's now look at how we read and convert our HTTP message into a Java object:
Object
readFrom
(
Class
<
Object
>,
Type genericType
,
Annotation annotations
[],
MediaType mediaType
,
MultivaluedMap
<
String
,
String
>
httpHeaders
,
InputStream entityStream
)
throws
throws
IOException
,
WebApplicationException
{
try
try
{
JAXBContext ctx
=
JAXBContext
.
newInstance
(
type
);
return
return
ctx
.
createUnmarshaller
().
unmarshal
(
entityStream
);
}
catch
catch
(
JAXBException ex
) {
throw
throw new
new
RuntimeException
(
ex
);
}
}
The
readFrom()
method gives us access to the HTTP headers of the incoming request as
well as a
java.io.InputStream
that represents the request message body. Here, we just cre-
ate a
JAXBContext
based on the Java type we want to create and use a
javax.xml.bind.Unmarshaller
to extract it from the stream.
Life Cycle and Environment
By default, only one instance of each
MessageBodyReader
,
MessageBodyWriter
, or
Con-
textResolver
is created per application. If JAX-RS is allocating instances of these compon-
ents (see
Chapter 14
), the classes of these components must provide a public constructor for
which the JAX-RS runtime can provide all the parameter values. A public constructor may
only include parameters annotated with the
@Context
annotation. For example:
@Provider
@Consumes
(
"application/json"
)
public
public class
class
MyJsonReader
MyJsonReader
implements
implements
MessageBodyReader
{
public
public
MyJsonReader
(
@Context
Providers providers
) {
this
this
.
providers
=
providers
;
}
}
Whether or not the JAX-RS runtime is allocating the component instance, JAX-RS will per-
form injection into properly annotated fields and setter methods. Again, you can only inject
JAX-RS objects that are found using the
@Context
annotation.