Monday, March 18, 2013

How-to: RESTful Web services with JAX-RS and Spring

When providing services in a specific technology (i.e. EJB, JAX-WS, JAX-RS), it's wise to avoid mixing the business logic of your service and the technology that you are using to expose it to the outside world. This separation facilitates easier adoption of newer technologies and makes it easier to maintain and test services.

Let's see how this will work by implementing a simple blogging system. The project is split into 3 maven modules:

service-java
Business logic of the service. Uses domain objects.
jaxrs-service-specification
Contains JAX-RS annotated service interfaces and DTO objects.
service-provider-jaxrs
Implements JAX-RS annotated interfaces.

service-java

The service module contains the business interface (illustrated below) and it's implementation. It's a POJO service and its operations can be unit tested.

jaxrs-service-specification

This module is service specific. It contains a JAX-RS annotated interface and DTO classes required to provide and/or consume RESTful this service.

service-provider-jaxrs

Provider module is usually a web module. It has a dependency to both of the above modules. This module implements the JAX-RS annotated interface and delegates to the service-java layer after carrying out technology specific aspects (i.e. validation, authentication) and mapping DTO objects to domain objects. In this way, we avoid exposing the internals of our domain structure to the outside world.

But before we are ready to deploy, we have to stitch our classes together. Spring and Jersey configuration is illustrated below, though other Resteasy and Apache CXF have similar setup for integrating with Spring.

The deploy-ready source code can be downloaded at my quickstarts repository, jaxrs-tutorial and tested using any RESTful service consuming tool.

1 comment: