Skip to content

Spring Dependency Injection

Joe Betz edited this page Aug 28, 2013 · 14 revisions

To bind rest.li’s dependency injection to spring. Use the two below classes, which are not yet added to the rest.li but may be added shortly and are available here under the apache 2.0 license.


/*
   Copyright (c) 2013 LinkedIn Corp.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.linkedin.restli.server.spring;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.linkedin.restli.internal.server.model.ResourceModel;
import com.linkedin.restli.server.resources.ResourceFactory;

/**
 * This is Spring specific {@link ResourceProvider}, which injects dependencies
 * to the resource classes, which are expressed using JSR-330 annotations.
 * This class delegates calls to the more general InjectResourceProvider, which
 * is declared in {@link com.linkedin.restli.server.resources.InjectResourceFactory}.
 * This class initialization order which occurs in Spring: first, when this class is
 * instantiated by Spring, {@link #setApplicationContext(ApplicationContext)} method is
 * invoked, later RestLi invokes {@link #setRootResources(Map)} method, which concludes
 * initialization process.
 *
 * @author jodzga
 */
public class InjectResourceFactory implements ResourceFactory, ApplicationContextAware
{
  private static final Logger log = LoggerFactory.getLogger(InjectResourceFactory.class);

  private com.linkedin.restli.server.resources.InjectResourceFactory _delegate;

  @Override
  public <R> R create(Class<R> resourceClass)
  {
    return _delegate.create(resourceClass);
  }

  @Override
  public void setApplicationContext(ApplicationContext ctx) throws BeansException
  {
    log.debug(String.format("Setting application context '%s'", ctx.getDisplayName()));
    _delegate = new com.linkedin.restli.server.resources.InjectResourceFactory(new SpringBeanProvider(ctx));
  }

  /**
   * @see com.linkedin.restli.server.spring.LinkedInSpringResourceFactory#setRootResources(java.util.Map)
   */
  @Override
  public void setRootResources(Map<String, ResourceModel> rootResources)
  {
    _delegate.setRootResources(rootResources);
  }

}

/*
   Copyright (c) 2013 LinkedIn Corp.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.linkedin.restli.server.spring;

import java.util.Map;
import org.springframework.context.ApplicationContext;
import com.linkedin.restli.server.resources.BeanProvider;

/**
 * @author Josh Walker
 * @version $Revision: $
 */

public class SpringBeanProvider implements BeanProvider
{
  private final ApplicationContext _context;

  public SpringBeanProvider(ApplicationContext context)
  {
    _context = context;
  }

  @Override
  public Object getBean(String name)
  {
    return _context.getBean(name);
  }

  @Override
  public <T> Map<String, T> getBeansOfType(Class<T> clazz)
  {
    return _context.getBeansOfType(clazz, false, true);
  }
}


/*
   Copyright (c) 2013 LinkedIn Corp.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.linkedin.restli.server.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

import com.linkedin.restli.server.RestLiServer;
import com.linkedin.restli.server.DelegatingTransportDispatcher;

import com.linkedin.r2.transport.http.server.RAPServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import java.io.IOException;

public class RestliSpringServlet implements HttpRequestHandler {

  private RAPServlet _r2Servlet;
  
  public RestliSpringServlet(RestLiServer restLiServer)
  {
    _r2Servlet = new RAPServlet(new DelegatingTransportDispatcher(restLiServer));
  }
  
  public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    _r2Servlet.service(req, res);
  }
}

Example Use:


package com.example.fortune.impl;

import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;

@Component
public class FortunesBean {

  static Map<Long, String> fortunes = new HashMap<Long, String>();
  static {
    fortunes.put(1L, "Today is your lucky day.");
    fortunes.put(2L, "There's no time like the present.");
    fortunes.put(3L, "Don't worry, be happy.");
  }
  
  public String getFortune(Long id)
  {
    return fortunes.get(id);
  }
}

package com.example.fortune.impl;

import com.linkedin.restli.server.annotations.RestLiCollection;
import com.linkedin.restli.server.resources.CollectionResourceTemplate;
import com.example.fortune.Fortune;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Very simple RestLi Resource that serves up a fortune cookie.
 *
 * @author Doug Young
 */
@RestLiCollection(name = "fortunes", namespace = "com.example.fortune")
public class FortunesResource extends CollectionResourceTemplate<Long, Fortune>
{
  @Inject @Named("fortunesBean")
  public FortunesBean _fortunesBean;

  @Override
  public Fortune get(Long key)
  {
    // Retrieve the requested fortune
    String fortune = _fortunesBean.getFortune(key);
    if(fortune == null)
      fortune = "Your luck has run out. No fortune for id="+key;

    // return an object that represents the fortune cookie
    return new Fortune().setFortune(fortune);
  }
}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>

<web-app>
  <display-name>Fortunes App</display-name>
  <description>Tells fortunes</description>

  <!-- spring DI -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/beans.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
  <!-- servlet definitions -->
  <servlet>
      <display-name>RestliSpringServlet</display-name>
      <servlet-name>restliSpringServlet</servlet-name>
      <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
  </servlet>

  <!-- servlet mappings -->
  <servlet-mapping>
      <servlet-name>restliSpringServlet</servlet-name>
      <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>


<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
    default-lazy-init="true">
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Scans within the base package of the application for @Components to configure as beans -->
    <!-- @Controller, @Service, @Configuration, etc. -->
    <context:component-scan base-package="com.example.fortune" />

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />
    
    <bean id="restConfig" class="com.linkedin.restli.server.RestLiConfig">
      <property name="resourcePackageNames" value="com.example.fortune.impl" />
    </bean>
    
    <bean id="resourceFactory" class="com.linkedin.restli.server.spring.InjectResourceFactory"/>
    
    <bean id="restliServer" class="com.linkedin.restli.server.RestLiServer">
      <constructor-arg ref="restConfig" />
      <constructor-arg ref="resourceFactory" />
    </bean>
    
    <bean id="restliSpringServlet" class="com.linkedin.restli.server.spring.RestliSpringServlet">
      <constructor-arg ref="restliServer" />
    </bean>
    
</beans>

Clone this wiki locally