Wiring RESTful web services with Spring

I’ve recently been using Spring 3.0M1 to make some RESTful APIs. While working on the project a question came up a few times from different people: how do the <jee:jndi-lookup/>, <context:annotation-config/> and <context:component-scan/> beans relate to each other? I’ve got some sample code that I use as a reference when this question comes up.

Let’s start with the <jee:jndi-lookup/> bean. Since a RESTful API probably runs in a web container we need to look up a data source, persistence unit or persistence context. We define the persistence unit in WEB-INF/classes/META-INF/persistence.xml.

<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
  <persistence-unit name="bookmarksPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
    <non-jta-data-source>jdbc/bookmarks</non-jta-data-source>
    <class>net.anthonychaves.bookmarks.models.User</class>
    <class>net.anthonychaves.bookmarks.models.Bookmark</class>
  </persistence-unit>
</persistence>

The bookmarksPU persistence unit is registered with the container when the webapp is deployed. It looks up the jdbc/bookmarks datasource and uses it for access to the database. Setting up this datasource is up to you based on your container.

The bookmarksPU is also bound to a JNDI name, persistence/bookmarksPU. We can inject this persistence unit into our webapp in the form of an EntityManagerFactory after registering a bean in our Spring container. We do this in our Spring configuration file by looking up the persistence unit in JNDI.

<jee:jndi-lookup id="bookmarksPU" jndi-name="persistence/bookmarksPU"/>

In our service layer we have a class UserService.

@Service
public class UserService {

  @PersistenceUnit(unitName="bookmarksPU")
  EntityManagerFactory emf;

  public void saveUser(User user) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(user);
    em.getTransaction().commit();
  }

  public User findUser(String name) {
    EntityManager em = emf.createEntityManager();
    Query query = em.createQuery("select u from User u where u.name = ?1")
                    .setParameter(1, name);
    em.getTransaction().begin();
    User user = (User) query.getSingleResult();
    em.getTransaction().rollback();
    return user;
  }
}

Notice two things about this class: it is annotated with the org.springframework.stereotype.Service annotation and its EntityManagerFactory is annotated with the javax.persistence.PersistenceUnit annotation. We want Spring to deal with both of these annotations. We want the component, the class annotated by @Service, registered as a Spring bean without doing it manually in XML. We also want Spring to inject an instance of EntityManagerFactory bound to the persistence/bookmarksPU persistence unit.

One of the nice things about Spring is that we can rely on these annotations so we don’t have to create long XML configuration files. We still need the XML config to tell Spring which classes it should examine for these annotations. Enter the <context:annotation-config/> and <context:component-scan/> beans.

Each of these beans implicitly creates instances of classes that implement the BeanPostProcessor interface. The post processor created by the <context:annotation-config/> bean that is most important to our case is the PersistenceAnnotationPostProcessorBean. This bean finds the bookmarksPU bean created when we performed the JNDI lookup and injects it into the emf field annotated with @PersistenceUnit.

The <context:annotation-config/> bean takes care of the javax.persistence annotation but it does not create a bean definition for the UserService class. To do that we need the <context:component-scan/> bean. This bean scans the specified base package for classes annotated with @Component and its subclasses, which includes @Service. By annotating the UserClass as a @Service we are spared from configuring it by hand in XML.

The <context:component-scan/> bean only searches for annotations relevant to the current application context. In this case we must define the service layer outside of the *-servlet.xml WebApplicationContext. The @Controller annotation is valid in a WebApplicationContext where a @Service annotation is not. We should instead keep our service layer configuration separate from the webapp configuration. In services.xml we have our services defined.

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       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/jee

                           http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">

  <jee:jndi-lookup id="bookmarksPU" jndi-name="persistence/bookmarksPU"/>

  <!-- here we need component-scan for the services and annotation-config for the persistence unit -->
  <context:component-scan base-package="net.anthonychaves.bookmarks"/>
  <context:annotation-config/>

</beans>

A WebApplicationContext inherits all the bean definitions from any imported ApplicationContexts. If we import the services.xml file in our *-servlet.xml file we will inherit the fully wired UserService bean created by the BeanPostProcessor beans in that ApplicationContext. We have a controller that needs an instance of UserService.

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	UserService userService;

	@Autowired
	ImageCaptchaService icservice;

	@RequestMapping(value="/new", method=RequestMethod.GET)
	public String newUser(ModelMap model) {
		model.addAttribute(new User());
		return "user_new";
	}

	@RequestMapping(method=RequestMethod.POST)
	public String createUser(@ModelAttribute("user") User user,
							 HttpSession session,
							 @RequestParam("j_captcha_response") String captchaResponse) {

		boolean validResponse = icservice.validateResponseForID(session.getId(), captchaResponse);
		if (validResponse) {
		  userService.saveUser(user);
		  session.setAttribute("user", user);
			return "redirect:/b/user";
		} else {
			return "redirect:/b/user/new";
		}
	}

	@RequestMapping(method=RequestMethod.GET)
	public String user(HttpSession session) {
	  if (session == null || session.getAttribute("user") == null) {
	    return "redirect:/b/user/new";
	  }

		User user = (User)session.getAttribute("user");
	  return "user";
	}

	@RequestMapping(method=RequestMethod.POST, value="/login")
	public String login(@RequestParam("name") String username, HttpSession session) {
	  User user = userService.findUser(username);
	  session.setAttribute("user", user);
    return "redirect:/b/user";
	}

	public void setUserService(UserService userService) {
	  this.userService = userService;
	}
}

By specifying the UserService in UserController as @Autowired we expect an AutowiredAnnotationBeanPostProcessor to inject an instance of UserService into an instance of this class. Both the <context:annotation-config/> and <context:component-scan/> beans create instances of AutowiredAnnotationBeanPostProcessor. The <context:annotation-config/> bean creates a PersistenceAnnotationBeanPostProcessor which is not important to us here. We don’t have any persistence units to inject.

The <context:component-scan/> bean creates an AutowiredAnnotationBeanPostProcessor and it also registers a bean definition for the UserController. @Controller is a subclass of @Component and has several annotations that would only be used in a class annotated with @Controller. The <context:component-scan/> bean takes care of mapping any routes and parameters specified by the @RequestMapping, @RequestParam and other @Controller-related annotations.

Our bookmarks-servlet.xml file needs only the <context:component-scan/> bean defined to get our web classes up and running. The full bookmarks-servlet.xml file is very simple.

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       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/jee

                           http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">

  <import resource="services.xml"/>

  <!-- component-scan creates implicit AutowiredBeanPostProcessor,
             we don't need PersistenceAnnotationPostProcessor -->
  <context:component-scan base-package="net.anthonychaves.bookmarks"/>

  <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
  </bean>

  <bean id="captchaService" class="net.anthonychaves.bookmarks.service.CaptchaServiceSingleton"
        factory-method="getInstance"/>

</beans>

This should hopefully make it very easy for anyone to quickly create at least a skeleton RESTful API with Spring. Comments? Let me know!