Java Reference
In-Depth Information
@Consumes
(
"application/xml"
)
public
public
void
void
createCustomer
(
Customer cust
) {
...
}
}
As you can see, once you've applied JAXB annotations to your Java classes, it is very easy
to exchange XML documents between your client and web services. The built-in JAXB
handlers will handle any JAXB-annotated class for the
application/xml
,
text/xml
, or
ap-
plication/*+xml
media types. By default, they will also manage the creation and initializa-
tion of
JAXBContext
instances. Because the creation of
JAXBContext
instances can be ex-
pensive, JAX-RS implementations usually cache them after they are first initialized.
Managing your own JAXBContexts with ContextResolvers
If you are already familiar with JAXB, you'll know that many times you need to configure
your
JAXBContext
instances a certain way to get the output you desire. The JAX-RS built-in
JAXB provider allows you to plug in your own
JAXBContext
instances. The way it works is
that you have to implement a factory-like interface called
javax.ws.rs.ext.ContextResolver
to override the default
JAXBContext
creation:
public
public interface
interface
ContextResolver
ContextResolver
<
T
> {
T
getContext
(
Class
<?>
type
);
}
ContextResolvers
are pluggable factories that create objects of a specific type, for a certain
Java type, and for a specific media type. To plug in your own
JAXBContext
, you will have to
implement this interface. Here's an example of creating a specific
JAXBContext
for our
Cus-
tomer
class:
@Provider
@Produces
(
"application/xml"
)
public
public class
class
CustomerResolver
CustomerResolver
implements
implements
ContextResolver
<
JAXBContext
> {
private
private
JAXBContext ctx
;
public
public
CustomerResolver
() {
this
this
.
ctx
= ...;
// initialize it the way you want
}
public
public
JAXBContext
getContext
(
Class
<?>
type
) {
iif
(
type
.
equals
(
Customer
.
class
)) {