Oops Null Pointer

Java programming related

Wiring Restlet JaxRs application with Spring

When wiring a JaxRs application from Spring I got most of the way using this post. My issue was different as  I already had a bean ref context for the rest of my application that I wanted to get my bean from.

I also wanted to respect the scope of the objects in the Spring configuration files and the example seemed to be always creating new instances when calling beanFactory.createBean(jaxRsClas).

The key was to convert the class name into a string and call beanFactory.getBean(classAsName) and then casting the bean it’s (generic) type.

import org.apache.commons.lang.StringUtils;

 * Uses application content and bean ref context in web.xml to wire each new object from Spring.
public class SpringRestletServlet extends ServerServlet {

  private static final Logger logger = Logger.getLogger(SpringRestletServlet.class);

   * Override the createApplication method to inject Spring objects
   * @param context - Restlet context
   * @return - application instance
  public Application createApplication(Context context) {
    JaxRsApplication app = (JaxRsApplication)super.createApplication(context);

    // set up spring to be the object creator
    app.setObjectFactory(new SpringObjectFactory(getWebApplicationContext().getAutowireCapableBeanFactory()));
    return app;

  private static class SpringObjectFactory implements ObjectFactory {
    private final AutowireCapableBeanFactory beanFactory;

    public SpringObjectFactory(AutowireCapableBeanFactory beanFactory) {
      this.beanFactory = beanFactory;

    public T getInstance(Class jaxRsClass) throws InstantiateException {
      logger.debug( "Wiring JAX-RS class [" + jaxRsClass + "] using Spring." );

      String classAsName = StringUtils.uncapitalize(jaxRsClass.getSimpleName());
      return castBeanToType(classAsName);

    private T castBeanToType(String classAsName) {
      return (T)beanFactory.getBean(classAsName);

  private WebApplicationContext getWebApplicationContext() {
    return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

And here is the related parts if the web.xml file that use the bean ref content that is on the classpath to get beans used by the rest of the application:





<!-- Restlet adapter -->

<!-- Catch all requests -->

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: