JAX-RS : Services Configuration
Configuring JAX-RS services programmatically
Some things to note:
- The JAXRSServerFactoryBean creates a Server inside CXF which starts listening for requests on the URL specified.
- Check the JAXRSServerFactoryBean API for methods for adding multiple root resources
- setResourceClasses() is for root resources only, use setProvider() or setProviders() for @Provider-annotated classes.
- By default, the JAX-RS runtime is responsible for the lifecycle of resource classes, default lifecycle is per-request. You can set the lifecycle to singleton by using following line:
- If you prefer not to let the JAX-RS runtime handle the resource class lifecycle for you (for example, it might be the case that your resource class is created by other containers such as Spring), you can do the following:
The following example shows how to configure a JAX-RS endpoint in OSGI containers supporting Blueprint:
Configuring JAX-RS endpoints programmatically without Spring
Note that even though no Spring is explicitly used in the previous section, it is still used by default to have various CXF components registered with the bus such as transport factories. If no Spring libraries are available on the classpath then please follow the following example :
Configuring JAX-RS services in container with Spring configuration file.
In web.xml one needs to register one or more CXFServlet(s) and link to an application context configuration.
Using Spring ContextLoaderListener
The application context configuration is shared between all the CXFServlets
Using CXFServlet init parameters
Each CXFServlet can get a unique application context configuration. Note, no Spring ContextLoaderListener is registered in web.xml in this case.
In the above configuration all resources will be configured as singletons, see below for information on creating per-request resources.
Configuring JAX-RS services using explicit bean configuration
Note that jaxrs:server (and jaxrs:client) declarations depend on 'http://cxf.apache.org/jaxrs' Spring NamespaceHandler be available on classpath. Sometimes, due to classloading restrictions or bugs in underlying containers which are exposed during complex deployments or due to multiple Spring libraries interfering with each other, NamespaceHandler can not be located and thus jaxrs endpoints can not be created.
Please report such issues to the team working on developing the container itself.
If you need to do Spring configuration and get an error to do with a missing NamespaceHandler then, as a workaround, consider configuring jaxrs endpoints using CXF beans which actually handle the creation of jaxrs:server endpoints. This is marginally more complex, but overall, the configuration ends up being quite similar, for example, the above jaxrs:server endpoint can be configured like this instead:
CXF JAX-RS is capable of working with AOP interceptors applied to resource classes from Spring.
Note that some AOP configuration is applied to two JAX-RS resource classes. By default Spring uses JDK dynamic proxies if a class to be proxified implements at least one interface or CGLIB proxies otherwise.
For example, here's how org.apache.cxf.systest.jaxrs.BookStoreWithInterface looks like:
In this case Spring will use a JDK dynamic proxy to wrap a BookStoreWithInterface class. As such it is important that the method which needs to be invoked such as getThatBook(...) will be part of the interface.
The other method, getTheBook() can not be dispatched to by a JAX-RS runtime as it's not possible to discover it through a JDK proxy. If this method also needs to be invoked then this method should either be added to the interface or CGLIB proxies have to be explicitly enabled (consult Spring AOP documentation for more details). For example:
Configuring JAX-RS services in container without Spring
If you prefer, you can register JAX-RS endpoints without depending on Spring with the help of CXFNonSpringJaxrsServlet :
When service classes and providers are registered this way, the default life-cycle is 'singleton'. You can override it by setting a "jaxrs.scope" parameter with the value of 'prototype' (equivalent to per-request).
By default, the endpoint address is "/". One can provide a more specific value using a "jaxrs.address" parameter.
If the referenced service classes are not annotated with JAX-RS annotations then an external user model can also be linked to :
A more portable way to register resource classes and providers with CXFNonSpringJaxrsServlet is to use a JAX-RS Application implementation :
Note that Application.getClasses() method returns a set of per-request resource class names. Application.getSingletons() returns a list of singleton resource and provider classes.
Starting from CXF 2.3.7/2.4.3/2.5.0 it is possible to simple properties for resource and Application classes, providers and interceptors:
In the above example, org.apache.cxf.systest.jaxrs.BookApplication is expected to have setName and setId setters, with a single primitive or List parameter type.
Note that having the web-app_2_3.dtd DTD referenced from web.xml will likely prevent 'param-value' containing spaces and make it difficult to specify multiple providers like this:
In such cases consider moving to the web-app 2.5 schema or extending CXFNonSpringJaxrsProviders or introducing an Application.
Attaching JAXRS endpoints to an existing Jetty server
Here is a code fragment showing how it can be done with the help of CxfNonSpringJaxrsServlet :
JAX-RS RuntimeDelegate and Applications
If you have a JAX-RS Application implementation available and would like to minimize the interaction with the CXF JAX-RS specific API, you may want to use the JAX-RS RuntimeDelegate :
Note that the above code makes sure an @ApplicationPath value (if CustomApplication has this annotation) is taken into account.
Configuring JAX-RS services programmatically with Spring configuration file.
When using Spring explicitly in your code, you may want to follow this example :
Note that in in this case your Spring configuration file should import cxf-extension-http-jetty.xml instead of cxf-servlet.xml :
By default, the service beans which are referenced directly from the jaxrs:server endpoint declarations are treated by the runtime as singleton JAX-RS root resources. For example:
Spring instantiates and injects the customerBean reference and the runtime will access this reference directly afterwards. Effectively, the scope attribute which may be present on the customerBean bean declaration is ignored in this case, unless the Spring AOP is used to enforce the required scope (see below for more information).
The 'serviceFactories' element or beanNames attribute has to be used for a 'prototype', 'request' and other Spring bean scopes be supported.
For example, the serviceFactories element can reference one or more beans of type 'org.apache.cxf.jaxrs.spring.SpringResourceFactory' which in turn reference the actual service beans.
In this example, the jaxrs:server endpoint has two JAX-RS root resources (customerBean1 and customerBean2) with the Spring 'prototype' scope.
Other scopes can also be supported.
If using the jaxrs:serviceFactories element seems a bit verbose then the 'beanNames' attribute can be used instead:
The beanNames attribute lists the names/ids of service beans separated by space. The jaxrs:serviceFactories element has to be used when users register custom CXF JAX-RS ResourceProvider implementations.
Another approach toward supporting complex scopes in Spring is to use Spring AOP. For example, the following fragment shows how to have the Spring "request" scope supported:
in addition, the following servlet listener has to be added to the web.xml:
The request-scoped service bean instances (example, org.apache.cxf.systest.jaxrs.CustomerService instances) are not actually available at the initialization time thus one limitation of the above configuration is that it is not possible to inject JAX-RS contexts into these service beans. This is not a show-stopper because contexts such as UriInfo can be passed in as resource method parameters. However, if the injection into the fields or via method setters is required then a little customization of the org.apache.cxf.jaxrs.spring.SpringResourceFactory will do the trick. Particularly, the Spring ApplicationContext reports that a request-scoped bean is a singleton but the JAX-RS runtime can not inject thread-local proxies given that the actual instance is not available as explained above; in fact, the request-scoped beans are not really JAX-RS singletons. Thus a simple custom factory like this one is needed and it has to be used the following way:
The above configuration makes sure that the CXF JAX-RS runtime injects the values at the request time given that the customerBean bean is not seen as a JAX-RS singleton. This approach is only needed if the injection of contexts is required.
CXFNonSpringJaxrsServlet uses 'Singleton' as a default scope for service classes specified by a "jaxrs.serviceClasses" servlet parameter. It can be overridden by setting a "jaxrs.scope" parameter to a "prototype" value or by not using the "jaxrs.serviceClasses" parameter at all and registering a JAXRS Application implementation instead. Please see the section describing CXFNonSpringJaxrsServlet for more details.
CXFNonSpringJaxrsServlet can support singleton scopes for classes with constructors expecting JAXRS contexts, at the moment it can only inject ServletContext or ServletConfig contexts :
PostConstruct and PreDestroy
Bean methods annotated with @PostConstruct and @PreDestroy annotations will be called as expected by the scope rules.
Singleton beans will have their postconstruct method called when the endpoint is created. If a given singleton resource instance was created by Spring then its predestroy method will also be called after, for example, the web application which uses it is about to be unloaded. At the moment singletons created by CXFNonSpringJaxrsServlet or programmatically will only have their postconstruct method (if any) called.
Prototype beans will have their postconstruct and predestroy method called before a resource method is invoked and immediately after the invocation has returned but before the response has actually been serialized. You can indicate that the predestroy method has to be called after the request has completely gone out of scope (that is after the response body if any has been written to the output stream) by adding an "org.apache.cxf.jaxrs.service.scope" property with the value set to "request".
You can also register a custom Spring resource factory by extending org.apache.cxf.jaxrs.spring.SpringResourceFactory or providing a more sophisticated implementation.
Locating custom resources in web applications
Resources like schemas, custom XSLT templates and user models are typically referenced using a classpath: prefix. Thus one can add them to a WEB-INF/classes folder in a given web application.
Since CXF 2.2.3 one can put them directly under WEB-INF, for example into WEB-INF/xslt, WEB-INF/schemas, WEB-INF/model and referencing them like 'classpath:/WEB-INF/xslt/template.xsl'.
Multiple endpoints and resource classes
One can configure as many jaxrs:server endpoints as needed for a given application, with every endpoint possibly providing an alternative path to a single resource bean. Every endpoint can employ as many shared or unique resource classes as needed, and have common or different providers.
Sharing providers between multiple endpoints
One way to share multiple providers between multiple endpoints is to refer to the same provider bean from within jaxrs:provider sections:
Starting from CXF 2.7.2 it is possible to register provider directly on the bus as the bus properties and share them between all the providers using this bus:
Note a global exception mapper has been registered using the name of interface, "javax.ws.rs.ext.ExceptionMapper", which all the exception mappers have to implement.
Note that once can register global per-bus providers using "javax.ws.rs.ext.ExceptionMapper", "javax.ws.rs.ext.MessageBodyReader" or "javax.ws.rs.ext.MessageBodyWriter" bus properties with the registered providers expected to implement either of these interfaces.
Alternatively, one can have all the providers (JAX-RS and CXF-specific) registered with a bus using "org.apache.cxf.jaxrs.bus.providers" list property:
Dynamic servlets and a single JAX-RS endpoint
Note: this is not required by default starting from CXF 3.0.0-milestone1
In some advanced cases you may want to dynamically add new servlets (CXFServlet or CXFNonSpringJaxrsServlet) with all of them serving the same JAX-RS endpoints. In this case you most likely want to configure servlets so that the CXF endpoint address is not overridden :
Servlet and Application Container Configuration
Please see this page for more information.