The JerseyServlet simplifies the approach outlined in Use Jersey to provide REST APIs from karaf applications.
The JerseyServlet extends the Jersey ServletContainer to add two things:
- A default value for the list of Java packages that are scanned for Jersey resources (classes implementing REST API endpoints)
- A map of OSGi services to service implementations that will be used to register DS service injections with the HK2 dependency injection container, so they can be injected into the jersey resources
The default value for resources is the subpackage “.resources” of the package the DS component recides in. I.e. if the DS component is defined like this:
then no.priv.bang.demos.jerseyinkaraf.webapi.resources will be scanned for resources implementing REST API endpoints.
HK2 dependency injection of OSGi services are done in the following way:
- The DS component gets OSGi service injections for the services it needs to pass to the resources
Note: The LogService gets special treatment, since it used by the servlet itself to log problems adding services to HK2, but it is added to HK2 itself as well
- The resources uses @Inject annotations to get the services injected when jersey creates the resources in response to REST API invocations
To use JerseyServlet in a web whiteboard DS component residing in an OSGi bundle created by maven add the following dependencies:
The feature xml dependency is used by the karaf-maven-plugin to create a karaf feature file that can be used to pull in an OSGi bundle and all of its runtime dependencies into a karaf instance.
The <provided> dependencies are needed for compilation. Since provided dependencies aren’t transitive, all of the dependencies needed to resolve the classes are needed. E.g. the maven dependency containing the JerseyServlet’s parent class must be listed explicitly, even though that class isn’t used in the java source code. But without this dependency the code won’t compile.
- The maven-bundle-plugin will create imports for the packages of the classes used from provided dependencies in the bundle’s manifest.mf file
- The karaf-maven-plugin will not add provided bundles as bundles to be loaded in the features i generates and attaches to maven bundle projects, and instead add feature dependencies to features that load the bundles (