jprism
jprism

Reputation: 3494

Resource or Restlet

I am using Restlet 2.2.1 and building Rest services. As you know, Router is used to attach either Restlet or Resource as target.

Router router = new Router( getContext() );

router.attach("/healthcheck1",HealthCheckResource.class );
router.attach("/healthcheck2", new HealthCheckRestlet() );

Then you can implement your logic in handle()

Wondering which is best one to use? I know Resource has a very definite life cycle (doInit, handle, release ...) and good place to implement one time logic like initialization.

Upvotes: 1

Views: 76

Answers (1)

Tim Peierls
Tim Peierls

Reputation: 390

Attach a ServerResource subclass rather than a Restlet instance when feasible, for a couple of reasons:

  • Resources are the natural way to structure RESTful APIs. When you use the @Get, @Put, etc. annotations on a resource class, you're effectively documenting that part of your RESTful API, and there are tools that can extract that information to create online documentation automatically. If you use a Restlet instance, its behavior in response to GET, PUT, etc. is not immediately apparent. Ironically, using a Restlet makes it easier to write APIs that are not RESTful.

  • A separate instance of the resource class is created for each request, meaning that an instance is normally confined to a single thread, which simplifies reasoning about thread-safety. In constrast, the same Restlet instance will be used for all handle(...) calls, potentially leading to complicated thread-safety requirements.

Because each request gets its own resource instance, the resource methods might need to appeal to internal services that are passed via the application context or injected into the resource (see this Restlet extension).

Incidentally, your comment about "one time logic like initialization" might be a misunderstanding. The doInit method is called for each instantiated resource (i.e., once per request for that resource), not one time only.

Note that I'm recommending against directly subclassing Restlet as an end target for a resource URL, except maybe for trivial resources. Using subclasses of Restlet is a different matter: Attaching a Filter which wraps a resource is fine.

Upvotes: 1

Related Questions