Getting started with Maven and Spring


This guide is a quick introduction to getting started with Maven and Spring, and shows the making of a “Hello World” application

The only requirements for this project is a text editor, a Java install, and Maven.

I shall start by introducing you to Maven, the quote below is taken from the What is Maven page on the Maven site.

Maven, a Yiddish word meaning accumulator of knowledge, was originally started as an attempt to simplify the build processes in the Jakarta Turbine project. There were several projects each with their own Ant build files that were all slightly different and JARs were checked into CVS. We wanted a standard way to build the projects, a clear definition of what the project consisted of, an easy way to publish project information and a way to share JARs across several projects.

If you are not familiar with it, don’t worry – you don’t need to be for this tutorial. Hopefully though, this tutorial will show you enough of Maven to encourage you to find out more about it. The use of it here might seem a bit pointless and over the top, but it will simplify your build process, downloading all required Jar files for you and providing a simple build system.

So, assuming you have maven installed, you can create yourself a project by tying the following command. For the purpose of this tutorial, all you really need to understand from this command is that the ‘groupId’ will be your namespace, and the ‘artifactId’ will be the directory used for your project. Obviously, feel free to modify them – if you do so you will have to update any related references though out the rest of the article.

$ mvn archetype:generate --batch-mode \
  -DarchetypeArtifactId=maven-archetype-quickstart \ 
  -DgroupId=uk.co.pookey.spring \
  -DartifactId=spring-hello \
  -Dversion=1.0-SNAPSHOT
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...

You should now have a directory called spring-hello/. Change directory into this, and have a look around. You should notice that there’s a pom.xml and a src folder for your main and test source trees. You should notice that there is a “Hello World” example, which can be found in src/main/java/uk/co/pookey/spring/App.java and is shown below:

package uk.co.pookey.spring;
 
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

pom.xml is the file used by maven to specify dependencies, amongst other things. We’re going to add a little bit to this file now so that we can easily run our application though maven.

<project .....
...
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>java</goal>
            </goals>
          </execution>
        </executions>
 
        <configuration>
          <mainClass>uk.co.pookey.spring.App</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Once you have modified the pom.xml as described above, you should now be able to run your new project by typing mvn exec:java, but before doing so, you’ll need to mvn compile to compile the code. You should see something similar to the output below.

$ mvn compile
[INFO] Scanning for projects...
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Fri Sep 05 19:50:45 BST 2008
[INFO] Final Memory: 5M/12M
[INFO] ------------------------------------------------------------------------
 
$ mvn exec:java
...
[INFO] [exec:java]
Hello World!

Our next step is to tell Maven that we want to use Spring. Maven makes this wonderfully easy for us. First, we visit http://www.mvnrepository.com/ to find what we’re looking for. Searching for ‘spring’ on there gives quite a few results, but it’s http://www.mvnrepository.com/artifact/org.springframework/spring we’re interested in. Scrolling down that page we can see an XML snippet – which will need adding to our pom.xml within the <dependencies> section.

<dependencies>
    ...
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring</artifactId>
      <version>2.5.5</version>
    </dependency>
  </dependencies>

Next time you type mvn compile maven will download Spring, and any of Spring’s own dependencies, it takes care of everything!

Our next step, is to create a new class that we will use to saying hello to a specified name. The class is pretty simple, and we’ll place it in src/main/java/uk/co/pookey/SayHello.java

package uk.co.pookey;
 
public class SayHello
{
 
  private String name;
 
  public void setName(String name)
  {
    this.name = name;
  }
 
  public String getName()
  {
    return name;
  }
 
  public void greet()
  {
    System.out.println("Hello " + getName());
  }
 
}

Spring is configured via an XML file, which we’ll use to define out ‘beans’. We’re going to put the config file in src/main/resources/application=context.xml. The src/main/resources directory will need to be created first.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
   "http://www.springframework.org/dtd/spring-beans.dtd">
 
<beans>
  <bean id="hello" class="uk.co.pookey.SayHello">
    <property name="name" value="Pookey" />
  </bean>
</beans>

As you can see from the above, we are telling Spring we want the bean known as ‘hello’ to be of type uk.co.class.SayHello and that the property ‘name’ should be set to ‘Pookey’. Spring will take care of calling setName with the specified value when the bean is created. The updated App class.

package uk.co.pookey.spring;
 
import uk.co.pookey.SayHello;
 
import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
 
public class App
{
    public static void main( String[] args )
    {
      BeanFactory factory = new XmlBeanFactory(
          new ClassPathResource("application-context.xml"));
 
      SayHello hello = (SayHello) factory.getBean("hello");
      hello.greet();
    }
}

Now, all that’s left is to build and run our application, and see the exciting output that is generated. Simply type: mvn clean compile exec:java, and you should see this:

...
[INFO] Compiling 2 source files to /home/pookey/java/scratch/spring-hello/target/classes
[INFO] Preparing exec:java
[INFO] No goals needed for project - skipping
[INFO] [exec:java]
05-Sep-2008 20:59:22 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [application-context.xml]
Hello Pookey
...

This has of course been a very basic introduction to Spring and Maven, but hopefully it’s been enough to get you started. There’s plenty of books and tutorials for Spring, and I fully recommend you go and have a play!


Leave a comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

59 thoughts on “Getting started with Maven and Spring