Java Reference
In-Depth Information
Interfaces are a great way to scope out how you want to model your services. With an inter-
face, you can write something that defines what your RESTful API will look like along with
what Java methods they will map to before you write a single line of business logic. Also,
many developers like to use this approach so that their business logic isn't “polluted” with so
many annotations. They think the code is more readable if it has fewer annotations. Finally,
sometimes you do have the case where the same business logic must be exposed not only
RESTfully, but also through SOAP and JAX-WS. In this case, your business logic would
look more like an explosion of annotations than actual code. Interfaces are a great way to
isolate all this metadata into one logical and readable construct.
Let's transform our customer resource example into something that is interface based:
package
package
com
.
restfully
.
shop
.
services
;
import
import
...
...
;
@Path
(
"/customers"
)
public
public interface
interface
CustomerResource
CustomerResource
{
@POST
@Consumes
(
"application/xml"
)
public
public
Response
createCustomer
(
InputStream is
);
@GET
@Path
(
"{id}"
)
@Produces
(
"application/xml"
)
public
public
StreamingOutput
getCustomer
(
@PathParam
(
"id"
)
int
int
id
);
@PUT
@Path
(
"{id}"
)
@Consumes
(
"application/xml"
)
public
public
void
void
updateCustomer
(
@PathParam
(
"id"
)
int
int
id
,
InputStream is
);
}
Here, our
CustomerResource
is defined as an interface and all the JAX-RS annotations are
applied to methods within that interface. We can then define a class that implements this in-
terface:
package
package
com
.
restfully
.
shop
.
services
;
import
import
...
...
;
public
public class
class
CustomerResourceService
CustomerResourceService
implements
implements
CustomerResource
{
public
public
Response
createCustomer
(
InputStream is
) {