Ian P. Christian's Personal Blog Random witterings from pookey

5Sep/0857

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!

Filed under: geek, java Leave a comment
Comments (57) Trackbacks (2)
  1. Hi,
    You maven-archetype-quickstart as an archetype to base our application upon.
    Can you let us know what other archetypes are available?
    Is there any archetype to kickstart a spring application?
    Thanks,
    K

  2. if you type ‘mvn archetype:generate’ on it’s own, you get presented with a list of available options.

    Also, you might want to look at appfuse.

    Hope this helps!

  3. No doubt AppFuse is good. But the drawback is it not being upto date with the latest releases of various frameworks.

  4. In the last part of my hibernate tutorials I showed how to get a simple application inserting data into a database. This part doesn’t expand on that in terms of features, in fact, this tutorial actually does less! However, the last tutorial required

  5. Very nice tutorial for beginner !
    You can also replace the content of the App Class with this code:

    import org.springframework.context.support.ClassPathXmlApplicationContext;

    /**
    * Hello world!
    *
    */
    public class App
    {
    public static void main( String[] args )
    {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(“application-context.xml”);

    SayHello hello = (SayHello) ctx.getBean(“hello”);
    hello.greet();

    }
    }

  6. Quite a complete tutorial, grats!

  7. Good tutorial for beginners!

  8. thanx a lot! I thought, I’d spend the evening with configuring spring and maven; but with this tutorial it was made in 10 Minutes – great!

  9. Very simple and useful tutorial.

  10. Thank you! Very helpful for a beginner.

  11. Many thanks. I know Maven quite well and Spring a bit. I was just about putting together something like this on my own. Instead I can now just bookmark this page.

  12. Very good tutorial. you should do more like this .

  13. Great tutorial i understood the basics of spring and maven.

  14. Fantastic to start-up. Thanks many

  15. that was a great toturial , thanx.

  16. In this post I detail simple instructions for installing Glassfish v3 onto Ubuntu (although it will work just as well with Redhat, debian, and anything else). I also show how to create and deploy a simple WAR using Maven. Installing software

  17. Excellent tutorial!

    As a side-note I think that

    “application=context.xml” should be “application-context.xml”

  18. Erwin, you are correct. I just ran through this tutorial and also ran into that error.

  19. Thank you very much. Good intro.

  20. thx for the quick start — got me on my feet. :)

  21. Excellent tutorial. Was just looking for a tutorial of this kind. Simple, sweet, complete and working.

  22. Thank a lot Ian for the great example—you saved me hours and hours of work. Now I can get into the nitty-gritty details of Spring.

    cheers,

    Haneef

  23. A great startup for Beginners struggling to use maven and Spring.. Thanks a lot!!

  24. My turn to say that it was a perfect VERY SIMPLE tutorial for me and enable me to get introduced to the Spring spirit (and Maven too:)

  25. Tutorial is very simple and easily understood.
    Very much thanks.

  26. Simple short and sweet…. Thanks.

    Request more of such kind on hibernate and spring aswell…

  27. Thanks a lot for this sweet tutorial, you made my day

  28. Thanks for this simple WORKING example.

    Infact I started from scratch using the steps you detailed to get a textbook example working. The source code given by the authors was not working.

    Thanks for saving me so much time and effort.

    Regards,
    Prince

  29. Thanks. It’s comprehensible and simple and a start point for beginners like me.
    Do you recommend any tool (eclipse-netbeans..) to work integrated with maven and jspring?

    Regards

  30. Thanks for such a simple & complete example

  31. Thank you for a great tutorial! You distilled the maven setup to its essence!

  32. ApplicationContext ctx = new ClassPathXmlApplicationContext(“application-context.xml”);
    is it possible to use spring without “new ClassPathXmlApplicationContext(“application-context.xml”)” or any new instance?

  33. Great tutorial! Thanks.

  34. Very good tutorial. Thanx

  35. Great! Thank.

  36. Thank you! Great tutorial.

  37. Thx for the tutorial! =)

  38. Thanks for sharing! :)

  39. Thanks.

    A perfact tutorial for beginner.

    Thanks for sharing this.

  40. Very beginners tutorial!!.. I thinks you can use applicationcontex instead of BeanFactory, Today’s world, the use of BeanFactory is deprecated.

    Thanks for the tuto!

  41. This is great! Maven sure makes it easy :)

  42. very nice tut… I’ve been looking for something nifty to get me started and this most definitely did. I had to make a few changes to use version 3.1.0.RELEASE though –it would be nice if you could update your tutorial to reflect changes in later versions.

  43. Great tutorial for the beginners.Keep it up!

  44. Great tutorial!

  45. Thanks a lot. Great focus for the beginner

  46. Great article! Thanks.

  47. Thank you for this great and practical tutorial.
    It’s just what I needed!
    I’ve build it and run it as an eclipse project without any problem.
    Anyone wishing to have an export of the project, can contact me, of course.
    (It seems there is no way to attach a zip to the present blog)

  48. Great beginners tutorial. Thanks a lot for sharing.

  49. Thanks for this tutorial. It helps me a lot =)

  50. Very nice tutorial to quickly understand maven spring and be able to run a simple example. Thanks.


Leave a comment