<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ralf Schäftlein&#039;s Blog &#187; spring</title>
	<atom:link href="http://ralf.schaeftlein.de/tag/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://ralf.schaeftlein.de</link>
	<description>tech stuff, talk,...</description>
	<lastBuildDate>Sat, 27 Mar 2010 11:24:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>JUnit Tests for Spring 3 Rest Services</title>
		<link>http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-services/</link>
		<comments>http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-services/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 15:39:31 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[JAXB]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[webservices]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=187</guid>
		<description><![CDATA[SpringSource has recently released 3.0.1 of their Spring Framework. Spring 3 extended the REST functionalities inside the Web MVC part of the Framework. Rest Service are defined as Controller and can be tested with the new Resttemplate. In this little sample project is Spring 3 combined with JUnit 4, Maven, Hibernate 3.2, Jetty, MySQL, JPA, [...]]]></description>
			<content:encoded><![CDATA[<p>SpringSource has recently released <a href="http://blog.springsource.com/2010/02/18/spring-framework-3-0-1-released/">3.0.1</a> of their Spring Framework. Spring 3 extended the REST functionalities inside the Web MVC part of the Framework. Rest Service are defined as <a href="http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/">Controller</a> and can be tested with the new <a href="http://blog.springsource.com/2009/03/27/rest-in-spring-3-resttemplate/">Resttemplate</a>. In this little sample project is Spring 3 combined with JUnit 4, Maven, Hibernate 3.2, Jetty, MySQL, JPA, JAXB and AspectJ. Additional tests was made with <a href="https://addons.mozilla.org/de/firefox/addon/2691">Poster</a> as a Firefox Plugin to test REST bases Webservices. Jetty 6.1 is used as embedded container for the web application as backend for the seperated maven integration tests. Jetty can be started with mvn jetty:run for tests with Poster or will be started before the integration tests runs with mvn integration-test. The Project is configured via Maven pom.xml as seen later in this post. Via mvn eclipse:eclipse will the eclipse settings generated to use the project as WTP project. I used <a href="http://maven.apache.org/download.html">Maven 2.2.1</a> in combination with <a href="http://www.eclipse.org/downloads/">eclipse 3.5.2.</a>. As backend infrastructure runs inside Ubuntu 9.1 Server a <a href="http://www.bugzilla.org/">Bugzilla 3</a>, <a href="http://www.jfrog.org/products.php">Artifactory 2.2.1</a>, Subversion 1.6 and a <a href="http://hudson-ci.org/">Hudson 1.348</a>.</p>
<p>REST as <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">representational state transferr</a> has less protocol overhead as SOAP. It heavily depends on HTTP mechanism like PUT, GET, DELETE or POST method calls or HTTP accept header definition of the mime type like &#8216;text/xml&#8217;, &#8216;text/plain&#8217; or &#8216;image/jpeg&#8217; to define delivered and expected content. So you make a HTTP GET request with an accept header &#8216;image/jpeg&#8217; with a url like http://myserver/restservice/1 in firefox to see their a picture of catalog item with id 1. A HTTP Post send data to the server as new data and a PUT override existing data. HTTP 1.1 defines a <a href="http://http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">list of methods</a> to use in your REST based Service. </p>
<p>The whole project is Java annotation driven and use JDK 1.6 but can easily switched to run with JDK 1.5 as well. Configuration is Spring based as <a href="http://de.wikipedia.org/wiki/Inversion_of_Control">IOC pattern</a> and as annotations inside the Java classes. XML content is converted by JAXB Marshaller to use only domain objects inside your business logic. Persistence is defined as JPA annotations with Hibernate as implementation against a MySQL 5 database. The code was inspired by a blog from <a href="http://java.dzone.com/articles/spring-30-rest-example">Solomon Duskis</a>.</p>
<p><strong>The Java Source files</strong></p>
<p>The controller RestServiceController</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import de.schaeftlein.dev.spring.rest.dao.PersonDao;
import de.schaeftlein.dev.spring.rest.domain.People;
import de.schaeftlein.dev.spring.rest.domain.Person;

@Controller
@RequestMapping("/people")
public class RestServiceController
{
  @Autowired
  private PersonDao personDao;

  @RequestMapping(method = RequestMethod.GET)
  @Transactional(readOnly = true)
  @ResponseBody
  public People getAll() {
    List<Person> persons = personDao.getPeople();
    People people = new People(persons);
    return people;
  }

  @RequestMapping(value = "/person/{id}", method = RequestMethod.GET)
  @ResponseBody
  @Transactional(readOnly = true)
  public Person getPerson(@PathVariable("id") Long personId) {
    return personDao.getPerson(personId);
  }

  @RequestMapping(method = RequestMethod.POST)
  @Transactional(readOnly = false)
  @ResponseBody
  public Person savePerson(@RequestBody Person person) {
    personDao.savePerson(person);
    return person;
  }
}
</pre>
<p>The Interface for the DAO PersonDAO</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.dao;

import java.util.List;

import de.schaeftlein.dev.spring.rest.domain.Person;

public interface PersonDao {

  public Person getPerson(Long personId);

  public void savePerson(Person person);

  public List<Person> getPeople();

  public Person getPersonByUsername(String username);

}
</pre>
<p>The DAO implementation PersonDAOHibernate</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.dao.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import de.schaeftlein.dev.spring.rest.dao.PersonDao;
import de.schaeftlein.dev.spring.rest.domain.Person;

@Repository
@Transactional
@SuppressWarnings("unchecked")
public class PersonDaoHibernate extends HibernateDaoSupport implements
    PersonDao {

  @Autowired
  public void setupSessionFactory(SessionFactory sessionFactory) {
    this.setSessionFactory(sessionFactory);
  }

  public Person getPerson(Long personId) throws DataAccessException {
    return this.getHibernateTemplate().get(Person.class, personId);
  }

  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void savePerson(Person person) throws DataAccessException {
    this.getHibernateTemplate().saveOrUpdate(person);
  }

  public List<Person> getPeople() throws DataAccessException {
    return this.getHibernateTemplate().find("select people from Person people");
  }

  public Person getPersonByUsername(String username) {
    List<Person> people = this.getHibernateTemplate().findByNamedParam(
        "select people from Person people "
            + "where people.username = :username", "username", username);
    Person person = getFirst(people);
    if (person != null)
      getHibernateTemplate().evict(person);
    return person;
  }

  private static <T> T getFirst(List<T> list) {
    return CollectionUtils.isEmpty(list) ? null : list.get(0);
  }
}
</pre>
<p>The JAXB domain object People</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.domain;

import java.io.Serializable;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class People implements Serializable {
  private static final long serialVersionUID = 1L;

  private List<Person> person;

  public People() {
    // empty constructor required for JAXB
  }

  public People(List<Person> person) {
    this.person = person;
  }

  public List<Person> getPerson() {
    return person;
  }

  public void setPerson(List<Person> person) {
    this.person = person;
  }

}
</pre>
<p>The JAXB and JPA entity domain object Person</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.domain;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Version;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@XmlRootElement
public class Person implements Serializable
{
  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue
  private Long id;
  private String firstName;
  private String lastName;
  private String username;
  private String password;
  private int roleLevel;

  @Version
  private Integer version;

  public Person()
  {

  }

  public Person(String firstName, String lastName, String username, String password, int roleLevel)
  {
    this.firstName = firstName;
    this.lastName = lastName;
    this.username = username;
    this.password = password;
    this.roleLevel = roleLevel;
  }

  public Long getId()
  {
    return id;
  }

  public void setId(Long id)
  {
    this.id = id;
  }

  public String getFirstName()
  {
    return firstName;
  }

  public void setFirstName(String firstName)
  {
    this.firstName = firstName;
  }

  public String getLastName()
  {
    return lastName;
  }

  public void setLastName(String lastName)
  {
    this.lastName = lastName;
  }

  public String getUsername()
  {
    return username;
  }

  public void setUsername(String username)
  {
    this.username = username;
  }

  public String getPassword()
  {
    return password;
  }

  public void setPassword(String password)
  {
    this.password = password;
  }

  public int getRoleLevel()
  {
    return roleLevel;
  }

  public void setRoleLevel(int roleLevel)
  {
    this.roleLevel = roleLevel;
  }

  public Integer getVersion()
  {
    return version == null ? 1 : version;
  }

  public void setVersion(Integer version)
  {
    this.version = version;
  }

  public enum RoleLevel {
    ADMIN(1), GUEST(2), PUBLIC(3);
    private final int level;

    RoleLevel(int value)
    {
      this.level = value;
    }

    public static RoleLevel getLevel(String roleName)
    {
      return RoleLevel.valueOf(roleName);
    }

    public int getLevel()
    {
      return this.level;
    }
  }

  @Override
  public boolean equals(Object obj)
  {
    if (obj == null)
    {
      return false;
    }
    else if (!(obj instanceof Person))
    {
      return false;
    }
    else
    {
      Person p = (Person) obj;
      if (p.getId().equals(getId()) &#038;&#038; p.getUsername().equals(getUsername()) &#038;&#038;
          p.getVersion().equals(getVersion()) &#038;&#038;
          p.getLastName().equals(getLastName()) &#038;&#038; p.getPassword().equals(getPassword())
          &#038;&#038; p.getFirstName().equals(getFirstName()) &#038;&#038; p.getRoleLevel() == getRoleLevel())
      {
        return true;
      }
    }
    return false;
  }

}
</pre>
<p>The DAO test PersonDAOTest</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.dao;

import java.util.List;

import static junit.framework.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;

import de.schaeftlein.dev.spring.rest.domain.Person;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-context.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class PersonDaoTest {

  @Autowired
  PersonDao personDao;

  private Logger log = LoggerFactory.getLogger(PersonDaoTest.class);

  @Test
  public void testPerson() {
    String username = "jane.doe";
    Person person = new Person("Jane", "Doe", username, "password",
        Person.RoleLevel.ADMIN.getLevel());
    person.setVersion(1);
    personDao.savePerson(person);

    final List<Person> people = personDao.getPeople();
    assertEquals(1, people.size());
    assertEquals(person,people.get(0));

    Long personId = person.getId();
    Person savedPerson = personDao.getPerson(personId);
    assertEquals(username,savedPerson.getUsername());
  }

  @Test
  public void testVersion() {
    Person solomon = new Person("John", "Doe", "john.doe", "mypass",
        Person.RoleLevel.ADMIN.getLevel());
    // version 0
    personDao.savePerson(solomon);

    Integer version = solomon.getVersion();
    log.info("old version:"+solomon.getVersion());

    solomon = personDao.getPersonByUsername("john.doe");
    solomon.setPassword("password1");
    // version 1
    personDao.savePerson(solomon);

    log.info("new version:"+solomon.getVersion());

    assertTrue(!(version.equals(solomon.getVersion())));
  }
}
</pre>
<p>The Rest test RestClientTest</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.itest.controller;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;

import java.util.Collections;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.web.client.RestTemplate;

import de.schaeftlein.dev.spring.rest.domain.People;
import de.schaeftlein.dev.spring.rest.domain.Person;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-context.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class RestClientTest
{

  private static final String BASE_URL = "http://localhost:9090/spring3-rest-sample/people";

  private Logger log = LoggerFactory.getLogger(RestClientTest.class);

  @Autowired
  private RestTemplate restTemplate;

  @Test
  public void saveAndGet() throws Exception{
    // save
    Person input = new Person("jane","doe","jane.doe","pw",Person.RoleLevel.ADMIN.getLevel());
    assertNull(input.getId());
    Person output = restTemplate.postForObject(BASE_URL, input, Person.class, new Object[]{});
    assertNotNull("no person",output);
    assertNotNull(output.getId());
    assertEquals(input.getUsername(), output.getUsername());
    log.info("Saved jane.doe with id "+output.getId());
    // get all
    People people = restTemplate.getForObject(BASE_URL, People.class,new Object[]{});
    assertNotNull("no people",people);
    assertNotNull("no persons in people",people.getPerson());
    assertTrue("empty persons in people",!people.getPerson().isEmpty());
    assertEquals("no one person in people",input.getUsername(),people.getPerson().get(0).getUsername());
    log.info("Peple size "+people.getPerson().size());
    // get id
    Map<String, String> vars = Collections.singletonMap("id", output.getId()+"");
    Person idPerson = restTemplate.getForObject(BASE_URL+"/person/{id}", Person.class,vars);
    assertNotNull("no person",idPerson);
    assertNotNull(idPerson.getId());
    assertEquals(input.getUsername(), idPerson.getUsername());
    log.info("Get person by id <"+output.getId()+"> : "+idPerson.getUsername());
  }

}
</pre>
<p><strong>The configuration files</strong></p>
<p>The Spring annotation.xml</p>
<pre name="code" class='xml'>
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       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-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<!--
		Instruct Spring to perform declarative transaction management
		automatically on annotated classes.
	-->
	<tx:annotation-driven />
	<!--
		Activates various annotations to be detected in bean classes: Spring's
		@Required and @Autowired, as well as JSR 250's @PostConstruct,
		@PreDestroy and @Resource (if available) and JPA's @PersistenceContext
		and @PersistenceUnit (if available).
	-->
	<context:annotation-config />

	<!--
		Instruct Spring to retrieve and apply @AspectJ aspects which are
		defined as beans in this context (such as the UsageLogAspect below).
	-->
	<aop:aspectj-autoproxy />
</beans>
</pre>
<p>The JDBC settings jdbc.properties</p>
<pre name="code" class='xml'>
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=test
jdbc.password=test
jdbc.initialPoolSize=5
jdbc.maxPoolSize=100
jdbc.minPoolSize=5
jdbc.maxStatementsPerConnection=25
jdbc.maxStatements=50
jpa.databasePlatform=org.hibernate.dialect.MySQL5InnoDBDialect
jpa.showSql=true
jdbc.schema=test
jdbc.dataTypeFactory=org.dbunit.ext.mysql.MySqlDataTypeFactory
jdbc.autoCommitOnClose=true
jdbc.autoCommit=true
hibernate.release_mode=after_transaction
hibernate.hbm2ddl=create
hibernate.auto_close_session=true
hibernate.current_session_context_class=thread
hibernate.flush_before_completion=true
</pre>
<p>The JAXB marshalling.xml</p>
<pre name="code" class='xml'>
<?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:p="http://www.springframework.org/schema/p"
  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  xmlns:aop="http://www.springframework.org/schema/aop"
  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/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/jdbc

		   http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

  <bean id="marshallingHttpMessageConverter"
    class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"
    p:marshaller-ref="jaxb2Marshaller" p:unmarshaller-ref="jaxb2Marshaller" />

  <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
        <value>de.schaeftlein.dev.spring.rest.domain.Person</value>
        <value>de.schaeftlein.dev.spring.rest.domain.People</value>
      </list>
    </property>
  </bean>

</beans>
</pre>
<p>The AOP based transactionAdvices.xml</p>
<pre name="code" class='xml'>
<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

  <aop:config>
    <aop:pointcut id="serviceMethods"
            expression="execution(* dao.*Dao*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
  </aop:config>

  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="save*" propagation="REQUIRED"/>
      <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
    </tx:attributes>
  </tx:advice>

</beans>
</pre>
<p>The spring-dispatcher.xml</p>
<pre name="code" class='xml'>
<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:p="http://www.springframework.org/schema/p"
  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  xmlns:aop="http://www.springframework.org/schema/aop"
  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/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/jdbc

		   http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

  <import resource="transactionAdvices.xml" />
  <import resource="annotation.xml" />
  <import resource="marshalling.xml" />

  <bean
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

  <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
        <ref bean="marshallingHttpMessageConverter"/>
      </list>
    </property>
 </bean>

  <context:component-scan base-package="de.schaeftlein.dev.spring.rest.controller" />
</beans>
</pre>
<p>The spring-context.xml</p>
<pre name="code" class='xml'>
<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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
	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/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/jdbc

	http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

	<import resource="transactionAdvices.xml" />
	<import resource="annotation.xml" />
	<import resource="marshalling.xml" />

   <context:component-scan base-package="de.schaeftlein.dev.spring.rest" />

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters" ref="marshallingHttpMessageConverter"/>
    </bean>

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
			<value>${jdbc.driverClassName}</value>
		</property>
<property name="jdbcUrl">
			<value>${jdbc.url}</value>
		</property>
<property name="user">
			<value>${jdbc.username}</value>
		</property>
<property name="password">
			<value>${jdbc.password}</value>
		</property>
<property name="autoCommitOnClose">
			<value>${jdbc.autoCommitOnClose}</value>
		</property>
<property name="initialPoolSize">
			<value>${jdbc.initialPoolSize}</value>
		</property>
<property name="maxPoolSize">
			<value>${jdbc.maxPoolSize}</value>
		</property>
<property name="minPoolSize">
			<value>${jdbc.minPoolSize}</value>
		</property>
<property name="maxStatementsPerConnection">
			<value>${jdbc.maxStatementsPerConnection}</value>
		</property>
<property name="maxStatements">
			<value>${jdbc.maxStatements}</value>
		</property>
	</bean>

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
		p:location="classpath:jdbc.properties" />

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
		p:dataSource-ref="dataSource" p:lobHandler-ref="defaultLobHandler"
		p:packagesToScan="de.schaeftlein.dev.spring.rest.domain">
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.url">${jdbc.url}</prop>
<prop key="hibernate.connection.driver_class">${jdbc.driverClassName}</prop>
<prop key="hibernate.connection.password">${jdbc.username} </prop>
<prop key="hibernate.connection.username">${jdbc.password}</prop>
<prop key="hibernate.connection.autocommit">${jdbc.autoCommit}</prop>
<prop key="hibernate.connection.release_mode">${hibernate.release_mode}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl}</prop>
<prop key="hibernate.transaction.auto_close_session">${hibernate.auto_close_session}</prop>
<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">false</prop>
<prop key="hibernate.bytecode.provider">javassist</prop>
<prop key="hibernate.transaction.flush_before_completion">${hibernate.flush_before_completion}</prop>
			</props>
		</property>
	</bean>

	<bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" />

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager"
		p:sessionFactory-ref="sessionFactory" />   

</beans>
</pre>
<p>The web.xml</p>
<pre name="code" class='xml'>
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  version="2.4">

  <display-name>spring3-rest-sample</display-name>
  <description>Spring 3 Rest sample</description>
  <distributable />

  <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-context.xml</param-value>
  </context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

  <servlet>
    <servlet-name>springDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-dispatcher.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <!--
    - Dispatcher servlet mapping for the web user interface
  -->
  <servlet-mapping>
    <servlet-name>springDispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>
</pre>
<p>The Maven pom.xml</p>
<pre name="code" class='xml'>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>de.schaeftlein.dev.spring.rest</groupId>
	<artifactId>spring3-rest-sample</artifactId>
<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>spring3-rest-sample Maven Webapp</name>
	<description>A sample project for showing how to write JUnit Test against Spring 3 Rest Services</description>
    <developers>
     <developer>
       <name>Ralf Schäftlein</name>
       <url>http://ralf.schaeftlein.com</url>
     </developer>
    </developers>
    <inceptionYear>2010</inceptionYear>
    <issueManagement>
      <system>bugzilla</system>
      <url>http://ubuntu-vm.localdomain/cgi-bin/bugzilla3/index.cgi</url>
    </issueManagement>
    <url>http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-spring-3-rest-services</url>

	<reporting>
<plugins>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-report-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-checkstyle-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.6.1</version>
			</plugin>
<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.3</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<sourceEncoding>utf-8</sourceEncoding>
					<targetJdk>1.6</targetJdk>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jxr-plugin</artifactId>
				<version>2.1</version>
				<configuration>
<inputEncoding>UTF-8</inputEncoding>
					<outputEncoding>UTF-8</outputEncoding>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>taglist-maven-plugin</artifactId>
				<version>2.4</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-changes-plugin</artifactId>
				<version>2.3</version>
				<reportSets>
					<reportSet>
						<reports>
							<report>changes-report</report>
						</reports>
					</reportSet>
				</reportSets>
			</plugin>
		</plugins>
	</reporting>
	<distributionManagement>
		<repository>
			<id>internal</id>
			<url>
				dav:http://ubuntu-vm.localdomain:8081/artifactory/internal
			</url>
		</repository>
		<snapshotRepository>
			<id>snapshots</id>
			<url>
				dav:http://ubuntu-vm.localdomain:8081/artifactory/snapshots
			</url>
		</snapshotRepository>
	</distributionManagement>
	<scm>
		<connection>
           scm:svn:http://ubuntu-vm.localdomain/svn/
       </connection>
		<developerConnection>
           scm:svn:http://ubuntu-vm.localdomain/svn/
       </developerConnection>
		<url>http://ubuntu-vm.localdomain/svn/</url>
	</scm>
	<ciManagement>
		<system>Hudson</system>
		<url>http://ubuntu-vm.localdomain/hudson/job/spring3-rest-sample</url>
	</ciManagement>
	<build>
		<finalName>spring3-rest-sample</finalName>
<plugins>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-report-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-deploy-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<skip>true</skip>
				</configuration>
				<executions>
					<execution>
						<id>surefire-test</id>
<phase>test</phase>
						<goals>
							<goal>test</goal>
						</goals>
						<configuration>
							<skip>false</skip>
							<excludes>
								<exclude>**/itest/**</exclude>
							</excludes>
						</configuration>
					</execution>

					<execution>
						<id>surefire-itest</id>
<phase>integration-test</phase>
						<goals>
							<goal>test</goal>
						</goals>
						<configuration>
							<skip>false</skip>
							<includes>
								<include>**/itest/**</include>
							</includes>
						</configuration>
					</execution>
				</executions>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<sourceEncoding>utf-8</sourceEncoding>
					<targetJdk>1.6</targetJdk>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>check</goal>
							<goal>cpd-check</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.3</version>
				<configuration>
<formats>
<format>html</format>
<format>xml</format>
					</formats>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jxr-plugin</artifactId>
				<version>2.1</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-checkstyle-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>maven-jetty-plugin</artifactId>
				<version>6.1.22</version>
				<configuration>
					<scanIntervalSeconds>10</scanIntervalSeconds>
					<stopKey>foo</stopKey>
					<stopPort>9999</stopPort>
					<contextPath>/${artifactId}</contextPath>
					<connectors>
						<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>9090</port>
							<maxIdleTime>60000</maxIdleTime>
						</connector>
					</connectors>
				</configuration>
				<executions>
					<execution>
						<id>start-jetty</id>
<phase>pre-integration-test</phase>
						<goals>
							<goal>run</goal>
						</goals>
						<configuration>
							<scanIntervalSeconds>0</scanIntervalSeconds>
							<daemon>true</daemon>
						</configuration>
					</execution>
					<execution>
						<id>stop-jetty</id>
<phase>post-integration-test</phase>
						<goals>
							<goal>stop</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.8</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
					<wtpversion>2.0</wtpversion>
				</configuration>
			</plugin>
			<!--
				If you build jars the classpath of the referenced libraries will be
				added in the manifest.
			-->
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<!-- if you build jars a source file will be built as well -->
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.1.1</version>
				<executions>
					<execution>
						<id>attach-sources</id>
<phase>verify</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-scm-plugin</artifactId>
				<version>1.3</version>
				<configuration>
					<username>${svn_username}</username>
<password>${svn_password}</password>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.1-beta-1</version>
				<configuration>
					<warSourceDirectory>src/main/webapp</warSourceDirectory>
					<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
					<!-- we must exclude the svn folders -->
<packagingExcludes>
						<![CDATA[**/.svn,**/.svn/**,**/_svn,**/_svn/**]]&gt;
					</packagingExcludes>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib/</classpathPrefix>
						</manifest>
					</archive>
				</configuration>
			</plugin>
		</plugins>
		<!-- we must exclude the svn folders -->
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<excludes>
					<exclude>**/.svn</exclude>
					<exclude>**/.svn/**</exclude>
					<exclude>**/_svn</exclude>
					<exclude>_svn</exclude>
					<exclude>**/_svn/**</exclude>
				</excludes>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<directory>src/test/resources</directory>
				<excludes>
					<exclude>**/.svn</exclude>
					<exclude>**/.svn/**</exclude>
					<exclude>**/_svn</exclude>
					<exclude>_svn</exclude>
					<exclude>**/_svn/**</exclude>
				</excludes>
			</testResource>
		</testResources>
	</build>
<properties>
		<spring.framework.version>3.0.1.RELEASE</spring.framework.version>
		<org.slf4j.version>1.5.2</org.slf4j.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!--  AOP -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.2</version>
		</dependency>
		<!-- Spring  -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.framework.version}</version>
			<exclusions>
				<exclusion>
					<groupId>quartz</groupId>
					<artifactId>quartz</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>2.1_3</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>3.2.0.ga</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate</artifactId>
			<version>3.2.6.ga</version>
		</dependency>
		<dependency>
			<groupId>javax.persistence</groupId>
			<artifactId>persistence-api</artifactId>
			<version>1.0</version>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.11.0.GA</version>
		</dependency>

		<!-- Database -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.12</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>jta</artifactId>
			<version>1.1</version>
		</dependency>

		<!-- JAXB -->
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.0</version>
		</dependency>

		<!-- JUnit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
			<scope>test</scope>
		</dependency>
		<!--  logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>${org.slf4j.version}</version>
		</dependency>
		<!-- integration test -->
		<dependency>
			<groupId>org.mortbay.jetty</groupId>
			<artifactId>maven-jetty-plugin</artifactId>
			<version>6.1.15</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
</project>
</pre>
<p><strong>Sample Content for Poster</strong></p>
<p>The person.xml</p>
<pre name="code" class='xml'>
<?xml version="1.0" encoding="UTF-8"?>
<person>
    <firstName>Jane</firstName>
    <lastName>Doe</lastName>
    <username>jane.doe</username>
<password>bar</password>
    <roleLevel>2</roleLevel>
</person>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring 3.0 RC 2 and JSR-330 (Dependency Injection for Java)</title>
		<link>http://ralf.schaeftlein.de/2009/11/19/spring-3-0-rc-2-and-jsr-330-dependency-injection-for-java/</link>
		<comments>http://ralf.schaeftlein.de/2009/11/19/spring-3-0-rc-2-and-jsr-330-dependency-injection-for-java/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 18:03:59 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=159</guid>
		<description><![CDATA[SpringSource has published release candidate 2 of the upcoming 3.0 release of their Spring Framework. New Feature is the compliance with JSR-330 (&#8220;Dependency Injection for Java&#8221;). The JSR was developed together by Google (for their Guice Framework and SpringSource (for their Spring Framework) and is finally approved since 14.10.2009. A little example shows how to [...]]]></description>
			<content:encoded><![CDATA[<p>SpringSource has <a href="http://blog.springsource.com/2009/11/13/spring-framework-3-0-rc2-released/">published</a> release candidate 2 of the upcoming 3.0 release of their Spring Framework. New Feature is the compliance with <a href="http://jcp.org/en/jsr/detail?id=330">JSR-330</a> (&#8220;Dependency Injection for Java&#8221;). The JSR was developed together by Google (for their <a href="http://code.google.com/p/google-guice/">Guice</a> Framework and SpringSource (for their <a href="http://www.springsource.org/documentation">Spring Framework</a>) and is finally approved since 14.10.2009.</p>
<p>A little example shows how to develop services with interfaces and implementations without dependencies to Spring Framework or Google Guice: </p>
<p>
The Maven pom.xml</p>
<pre name="code" class='xml'>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>de.schaeftlein.dev</groupId>
	<artifactId>jsr330-sample</artifactId>
<packaging>jar</packaging>
	<name>jsr330-sample</name>
	<version>0.0.1-SNAPSHOT</version>
	<description>Sample App with Spring 3.0 RC 2 and JSR330</description>
<properties>
		<springVersion>3.0.0.RC2</springVersion>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-asm</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>jsr330-sample</finalName>
		<sourceDirectory>src/main/java</sourceDirectory>
		<testSourceDirectory>${basedir}/src/test/java</testSourceDirectory>

		<!-- we must exclude the svn folders -->
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<excludes>
					<exclude>**/.svn</exclude>
					<exclude>**/.svn/**</exclude>
					<exclude>**/_svn</exclude>
					<exclude>_svn</exclude>
					<exclude>**/_svn/**</exclude>
				</excludes>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<directory>src/test/resources</directory>
				<excludes>
					<exclude>**/.svn</exclude>
					<exclude>**/.svn/**</exclude>
					<exclude>**/_svn</exclude>
					<exclude>_svn</exclude>
					<exclude>**/_svn/**</exclude>
				</excludes>
			</testResource>
		</testResources>
<plugins>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<configuration>
					<downloadJavadocs>true</downloadJavadocs>
					<downloadSources>true</downloadSources>
					<excludes>
						<exclude>_svn</exclude>
						<exclude>.svn</exclude>
					</excludes>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<!-- if you build jars a source file will be built as well -->
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-sources</id>
<phase>verify</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>
</pre>
<p>
a simple encode/decode interface<br />
<P></p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring;

public interface Encryption
{
  String encode(String value);
  String decode(String value);
}
</pre>
<p>
a simple implementation for Encryption</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.inject.Named;

@Named // service name is the name of the class
public class URLEncoderEncyrption implements Encryption
{

  @Override
  public String decode(String value)
  {
    try
    {
      return URLDecoder.decode(value, "UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
      return null; // never happen
    }
  }

  @Override
  public String encode(String value)
  {
    try
    {
      return URLEncoder.encode(value, "UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
      return null; // never happen
    }
  }

}
</pre>
<p>
a more secure implementation for Encryption</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.inject.Named;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.sun.org.apache.xml.internal.security.utils.Base64;

@Named("secure") // named service bean
public class Base64Encyption implements Encryption
{
  private sun.misc.BASE64Encoder base64encoder;
  private SecretKey key;

  public Base64Encyption()
  {
    try
    {
      DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      key = keyFactory.generateSecret(keySpec);
      base64encoder = new BASE64Encoder();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  @Override
  public String decode(String input)
  {
    try
    {
      Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] bOut = cipher.doFinal(Base64.decode(input.getBytes("UTF-8")));
      return new String(bOut, "UTF-8");
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public String encode(String plainTextPassword)
  {
    try
    {
      byte[] cleartext = plainTextPassword.getBytes("UTF8");

      Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
      cipher.init(Cipher.ENCRYPT_MODE, key);
      return base64encoder.encode(cipher.doFinal(cleartext));
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }

}
</pre>
<p>
a small interface for a service</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

public interface SecureUtil
{
  void compareEncryption(String input);
}
</pre>
<p>
a implementation for our service</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

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

@Named("SecureUtil")
public class SecureUtilImpl implements SecureUtil
{
  @Inject // automatically set by DI framework
  @Named("secure") // get the namend bean
  private Encryption secureEncryption;

  @Inject // automatically set by DI framework
  @Named("URLEncoderEncyrption") // get the bean by its classname
  private Encryption unsecureEncryption;

  public void compareEncryption(String input){

    String encodedSecure = secureEncryption.encode(input);
    System.out.println("Secure encoded: "+encodedSecure);
    String encodeUnsecure = unsecureEncryption.encode(input);
    System.out.println("Unsecure encoded: "+encodeUnsecure);
    System.out.println("Secure decoded: "+secureEncryption.decode(encodedSecure));
    System.out.println("Unsecure decoded: "+unsecureEncryption.decode(encodeUnsecure));
  }
}
</pre>
<p>
finally a main class for testing</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main
{

  /**
   * main method
   */
  public static void main(String[] args)
  {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(Main.class.getPackage().getName()); // new way to get Application context without applicationContext.xml available
    SecureUtil util = ctx.getBean("SecureUtil", SecureUtil.class); // get bean with new generics method
    util.compareEncryption("an sample input string 1234567890");
  }

}
</pre>
<p>
output of our Main class</p>
<p><pre name="code" class='java'>
19.11.2009 18:56:03 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@c1b531: startup date [Thu Nov 19 18:56:03 CET 2009]; root of context hierarchy
19.11.2009 18:56:03 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
19.11.2009 18:56:03 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@a83b8a: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,secure,SecureUtil,URLEncoderEncyrption]; root of factory hierarchy
Secure encoded: QDQvd4uK14YNUQ4uoqhqsZEMDDxUqJAMyisvZr2wsA2GyMC5tSEIiw==
Unsecure encoded: an+sample+input+string+1234567890
Secure decoded: an sample input string 1234567890
Unsecure decoded: an sample input string 1234567890
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2009/11/19/spring-3-0-rc-2-and-jsr-330-dependency-injection-for-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dbunit with JUnit 4.x and Spring for testing Oracle DB Application</title>
		<link>http://ralf.schaeftlein.de/2009/01/05/dbunit-with-junit-4x-and-spring-for-testing-oracle-db-application/</link>
		<comments>http://ralf.schaeftlein.de/2009/01/05/dbunit-with-junit-4x-and-spring-for-testing-oracle-db-application/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 17:59:23 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[dbunit]]></category>
		<category><![CDATA[oracle]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=62</guid>
		<description><![CDATA[DBUnit is very nice for testing database content changes made by an application. You define in XML the data including the structure of your tables (dataset.xml). Simple_Data is the name of the table and each column is a attribute in the xml doc with the content value e.g. id with value 1. The Getting Started [...]]]></description>
			<content:encoded><![CDATA[<p>DBUnit is very nice for testing database content changes made by an application. You define in XML the data including the structure of your tables (dataset.xml).</p>
<p><pre name="code" class='xml'>
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
	<simple_data id="1" content="value_before"/>
</dataset>
</pre>
<p>
Simple_Data is the name of the table and each column is a attribute in the xml doc with the content value e.g. id with value 1.</p>
<p>
The <a href="http://dbunit.sourceforge.net/howto.html">Getting Started</a> of DBUnit work with JUnit 3.8 and self handling of the JDBC Connection.</p>
<p>
JUnit 4.x are more comfortable with annotations based test methods and Spring comes with dependency injection for separating<br />
configuration from implementation code.</p>
<p>
The following approach combines DBUnit with JUnit 4.4 and Spring 2.5.6 to test comfortable a Oracle 10g database.</p>
<p>
I use Maven 2.x to define the depending libraries used by the example (pom.xml):</p>
<p><pre name="code" class='xml'>
<?xml version="1.0" encoding="UTF-8"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<groupId>de.schaeftlein.dev.dbunit</groupId>
	<artifactId>test-dbunit</artifactId>
	<name>test-dbunit</name>
	<version>0.0.1-SNAPSHOT</version>
	<description />
	<dependencies>
		<dependency>
			<groupId>org.dbunit</groupId>
			<artifactId>dbunit</artifactId>
			<version>2.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring</artifactId>
			<version>2.5.6</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.4</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>2.5.6</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.14</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.2.0</version>
		</dependency>
	</dependencies>
</project>
</pre>
<p>
Keep in mind that the Oracle JDBC Driver has to be downloaded <a href="http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc_10201.html">manually</a>.<br />
The public maven repos include only the Pom definition for the oracle driver. Generate with maven command line tool the eclipse project files:
<p>
<code>mvn clean eclipse:clean eclipse:eclipse</code></p>
<p>
The JDBC datasource is defined via Spring (applicationContext.xml):
<p><pre name="code" class='xml'>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
	destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@10.0.0.2:1521:orcl" />
<property name="username" value="your_user_name" />
<property name="password" value="your_password" />
  </bean>
</beans>
</pre>
<p>
Additionally we define the expected data as well in XML for DBUnit (expectedDataSet.xml):
<p>
<P></p>
<pre name="code" class='xml'>
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
	<simple_data id="1" content="value_after"/>
</dataset>
</pre>
<p>
Now we can code our JUnit 4.x Test to
<ol>
<li>load data before the test method
<li>change the data via JDBC to emulate a application
<li>compare the changed data with expected data
<li>clean up the database
</ol>
<p><pre name="code" class='java'>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class TestDBUnitWithSpring {

	@Autowired
	private DataSource dataSource;

	@Before
	public void init() throws Exception{
		// insert data into db
		DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet());
	}

	@After
	public void after() throws Exception{
		// insert data into db
		DatabaseOperation.DELETE_ALL.execute(getConnection(), getDataSet());
	}

	private IDatabaseConnection getConnection() throws Exception{
	// get connection
		Connection con = dataSource.getConnection();
		DatabaseMetaData  databaseMetaData = con.getMetaData();
		// oracle schema name is the user name
		IDatabaseConnection connection = new DatabaseConnection(con,databaseMetaData.getUserName().toUpperCase());
		DatabaseConfig config = connection.getConfig();
		// oracle 10g
		config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new Oracle10DataTypeFactory());
		// receycle bin
		config.setFeature(DatabaseConfig.FEATURE_SKIP_ORACLE_RECYCLEBIN_TABLES, Boolean.TRUE);
		return connection;
	}

	private IDataSet getDataSet() throws Exception{
		// get insert data
		File file = new File("src/test/resources/dataset.xml");
		return new FlatXmlDataSet(file);
	}

	@Test
	public void testSQLUpdate() throws Exception{
		Connection con = dataSource.getConnection();
		Statement stmt = con.createStatement();
		// get current data
		ResultSet rst = stmt.executeQuery("select * from simple_data where id = 1");
		if(rst.next()){
			// from dataset.xml
			assertEquals("value_before", rst.getString("content"));
			rst.close();

			// update via sql
			int count = stmt.executeUpdate("update simple_data set content='value_after' where id=1");

			stmt.close();
			con.close();

			// expect only one row to be updated
			assertEquals("one row should be updated", 1, count);

			// Fetch database data after executing the code
			QueryDataSet databaseSet = new QueryDataSet(getConnection());
			// filter data
			databaseSet.addTable("simple_data", "select * from simple_data where id = 1");
			ITable actualTable = databaseSet.getTables()[0];

			// Load expected data from an XML dataset
			IDataSet expectedDataSet = new FlatXmlDataSet(new File("src/test/resources/expectedDataSet.xml"));
			ITable expectedTable = expectedDataSet.getTable("simple_data");

			// filter unnecessary columns of current data by xml definition
			actualTable = DefaultColumnFilter.includedColumnsTable(actualTable, expectedTable.getTableMetaData().getColumns());

			// Assert actual database table match expected table
			assertEquals(1,expectedTable.getRowCount());
			assertEquals(expectedTable.getRowCount(), actualTable.getRowCount());
			assertEquals(expectedTable.getValue(0, "content"), actualTable.getValue(0, "content"));

		} else {
			fail("no rows");
			rst.close();
			stmt.close();
			con.close();
		}

	}
}
</pre>
<p>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2009/01/05/dbunit-with-junit-4x-and-spring-for-testing-oracle-db-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>apache cxf 2.1 with spring 2, maven 2 and eclipse wtp</title>
		<link>http://ralf.schaeftlein.de/2008/05/04/apache-cxf-21-with-spring-2-maven-2-and-eclipse-wtp/</link>
		<comments>http://ralf.schaeftlein.de/2008/05/04/apache-cxf-21-with-spring-2-maven-2-and-eclipse-wtp/#comments</comments>
		<pubDate>Sun, 04 May 2008 14:38:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cxf]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[webservices]]></category>
		<category><![CDATA[wtp]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=11</guid>
		<description><![CDATA[Apache CXF 2.1 is released. I know XFire since a long time as web service provider. CXF is a merger of XFire with celtix, which provided an enterprise service bus. The main reason for choosing XFire rather then Axis was the WS-I BP compatibility. It&#8217;s a better arguing with a commercial eai provider when your [...]]]></description>
			<content:encoded><![CDATA[<p>Apache CXF 2.1 is <a href="http://cxf.apache.org/" target="_blank">released</a>. I know <a href="http://xfire.codehaus.org/" target="_blank">XFire</a> since a long time as web service provider.  CXF is a merger  of XFire with <a href="http://celtix.objectweb.org/" target="_blank">celtix</a>, which provided an enterprise service bus. The main reason for choosing XFire rather then Axis was the <a href="http://www.ws-i.org/" target="_blank">WS-I</a> BP compatibility. It&#8217;s a better arguing with a commercial eai provider when your webservice is at least WS-I BP 1.0 conform.  CXF is <a href="http://java.sun.com/webservices/technologies/index.jsp" target="_blank">JAX-WS 2.1</a> compatible. You can enable Pojo services with standard annotations as web services. To try that new release out i created with eclipse <a href="http://www.eclipse.org/webtools/" target="_blank">web tools platform</a> a new dynamic web project with <a href="http://tomcat.apache.org/" target="_blank">tomcat</a> 6 as web container.  First step is to add the libs needed for CXF. Normally i would download by myself the libs and copy it in to Web-inf/lib folder. Disk space is not a problem but you can&#8217;t share such projects by mail because of the size needed for the libs. So i use <a href="http://maven.apache.org/" target="_blank">maven 2</a> to define the needed libs.  The pom.xml define the project and its dependencies. Place it in the root of the project:</p>
<pre name="code" class="xml">
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0                       http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<groupId>de.schaeftlein.dev</groupId>
	<artifactId>cxf-sample</artifactId>
<packaging>war</packaging>
	<name>
	</name>
	<version>0.0.1-SNAPSHOT</version>
	<description>
	</description>
	<dependencies>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-core</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-frontend-simple</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-frontend-jaxws</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-databinding-aegis</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-local</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http-jetty</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-jms</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-management</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-common-utilities</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.mortbay.jetty</groupId>
			<artifactId>jetty</artifactId>
			<version>6.1.6</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring</artifactId>
			<version>2.0.8</version>
		</dependency>
	</dependencies>
	<build>
<plugins>
<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
		<defaultGoal>war:install</defaultGoal>
	</build>
</project>
</pre>
<p>So the libs are defined but nothing happened in eclipse. I use the <a href="http://m2eclipse.codehaus.org/" target="_blank">M2</a> Eclipse plugin. Now i enable maven with right click on the project and choose from M2 the &#8220;Enable dependency management&#8221; entry.  The plugin now download the libs into the local repository for all projects. In the eclipse build path you will find now a new library called &#8220;maven dependencies&#8221;. Eclipse WTP does not deploy out of the box this library. Inside the project configuration you will find a section called &#8220;j2ee module dependencies&#8221;. Just click the check box beside the &#8220;maven dependencies&#8221; library. Now all dependent libs are deployed as well.  As controller act the CXFServlet and for spring need a listener to be defined both in the web.xml:</p>
<pre name="code"  class="xml">
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>cxf-sample</display-name>
	<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>
		<servlet-name>CXFServlet</servlet-name>
		<servlet-class>
			org.apache.cxf.transport.servlet.CXFServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>CXFServlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>
</web-app>
</pre>
<p>I use <a href="http://springframework.org/" target="_blank">spring</a> as main configuration tool. CXF depends on spring 2.0.8. The beans.xml imports the default cxf settings and defines the HelloWorld service:</p>
<p>The web service has a interface:</p>
<pre name="code"  class="java">package demo.spring;

import javax.jws.WebService;

@WebService
public interface HelloWorld {
    String sayHi(String text);
}</pre>
<p>and a implementation:</p>
<pre name="code"  class="java">package demo.spring;

import javax.jws.WebService;

@WebService(endpointInterface = "demo.spring.HelloWorld")
public class HelloWorldImpl implements HelloWorld {

    public String sayHi(String text) {
        return "Hello " + text;
    }
}</pre>
<p>If not set up a local server during creation of the project you need to go to the servers tab in eclipse. Define a new server with server type &#8220;Tomcat v6.0 Server&#8221;. If the adapter does not appear click on the link to &#8220;download additional server adapters&#8221;. Under &#8220;installed runtime&#8221; should be a tomcat 6 server. If not you have to add a new runtime. For tomcat 6 i recommend at least java 1.5 as jre.  In the last step you can  directly add the  created project  for cxf.  Spring and CXF use commons logging for logging. So i provide in the classpath a simple log4j.xml to output everything interesting to std out:</p>
<pre name="code" class="xml">
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
	<appender name="ConsoleAppender"
		class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
				value="%d{ISO8601} %-5p %c - %m%n" />
		</layout>
	</appender>
	<category name="demo.spring">
<priority value="debug" />
	</category>
	<root>
<priority value="info" />
		<appender-ref ref="ConsoleAppender" />
	</root>
</log4j:configuration>
</pre>
<p>Setup and implementation are now done. So i started the server inside eclipse. The console should contains lines from spring configuring cxf.  To see  a list of deployed web services  just open a browser to http://localhost:8080/cxf-sample/services, where cxf-sample is the name of your eclipse project. You should see a list of links to the generated wsdl&#8217;s of the defined services. Copy the url to the HelloWorldImplPort in the clipboard.  For testing i use the free tool <a href="http://www.soapui.org/" target="_blank">soapui</a> which will be started and installed by <a href="http://www.soapui.org/jnlp/2.0.2/soapui.jnlp" target="_blank">webstart</a>. Choose under file the point &#8220;new wsdl project&#8221;. Give it a name and paste the url from the wsdl. Leave the tack for creating sample requests and choose ok. In the tree you see the project, the service, the operations and a request for each operation. Double Click on the only request for our service.  Replace the ? with a value of your own inside the arg0 tag and hit the green run button:</p>
<pre name="code"  class="xml">
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:spr="http://spring.demo/">
   <soapenv:Header/>
   <soapenv:Body>
      <spr:sayHi>
         <!--Optional:-->
         <!--type: string-->
         <arg0>John Doe</arg0>
      </spr:sayHi>
   </soapenv:Body>
</soapenv:Envelope>
</pre>
<p>You should see a response like that on right side of the request in a new window:</p>
<pre name="code"  class="xml">
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:sayHiResponse xmlns:ns2="http://spring.demo/">
         <return>Hello John Doe</return>
      </ns2:sayHiResponse>
   </soap:Body>
</soap:Envelope>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2008/05/04/apache-cxf-21-with-spring-2-maven-2-and-eclipse-wtp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
