Maven + Spring hello world example

This quick guide example uses Maven to generate a simple Java project structure, and demonstrates how to retrieve Spring bean and prints a “hello world” string.

Technologies used in this article :

  1. Spring 2.5.6
  2. Maven 3.0.3
  3. Eclipse 3.6
  4. JDK 1.6.0.13
Spring 3 example
For Spring 3, refer to this Maven + Spring 3 hello world example.

1. Generate project structure with Maven

In command prompt, issue following Maven command :

mvn archetype:generate -DgroupId=com.mkyong.common -DartifactId=SpringExamples 
	-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Maven will generate all the Java’s standard folders structure for you (besides resources folder, which you need to create it manually)

2. Convert to Eclipse project

Type “mvn eclipse:eclipse” to convert the newly generated Maven style project to Eclipse’s style project.

mvn eclipse:eclipse

Later, import the converted project into Eclipse IDE.

Create a resources folder
Create a resources “/src/main/resources” folder, the Spring’s bean xml configuration file will put here later. Maven will treat all files under this “resources” folder as resources files, and copy it to output classes automatically.

3. Add Spring dependency

Add Spring dependency in Maven’s pom.xml file.

File : pom.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>com.mkyong.common</groupId>
	<artifactId>SpringExamples</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SpringExamples</name>
	<url>http://maven.apache.org</url>
	<dependencies>
 
		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring</artifactId>
			<version>2.5.6</version>
		</dependency>
 
	</dependencies>
</project>

Issue “mvn eclipse:eclipse” again, Maven will download the Spring dependency libraries automatically and put it into your Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse “.classpath” for dependency purpose.

4. Spring bean (Java class)

Create a normal Java class (HelloWorld.java) at “src/main/java/com/mkyong/common/HelloWorld.java”. Spring’s bean is just a normal Java class, and declare in Spring bean configuration file later.

package com.mkyong.common;
 
/**
 * Spring bean
 * 
 */
public class HelloWorld {
	private String name;
 
	public void setName(String name) {
		this.name = name;
	}
 
	public void printHello() {
		System.out.println("Hello ! " + name);
	}
}

5. Spring bean configuration file

Create an xml file (Spring-Module.xml) at “src/main/resources/Spring-Module.xml“. This is the Spring’s bean configuration file, which declares all the available Spring beans.

File : Spring-Module.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<bean id="helloBean" class="com.mkyong.common.HelloWorld">
		<property name="name" value="Mkyong" />
	</bean>
 
</beans>

6. Review project structure

Review it and make sure the folder structure as follows

spring hello world example

7. Run It

Run App.java, it will load the Spring bean configuration file (Spring-Module.xml) and retrieve the Spring bean via getBean() method.

File : App.java

package com.mkyong.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class App {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"Spring-Module.xml");
 
		HelloWorld obj = (HelloWorld) context.getBean("helloBean");
		obj.printHello();
	}
}

8. Output

Hello ! Mkyong

Download Source Code

Download it – Spring-hello-world-example.zip (7KB)
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: Package name does not correspond to the file pathCopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns query, ()

  • Pingback: Maven | indybee83()

  • http://kampungkid.tumblr.com/ Cody

    Thanks, Mkyong. You’re awesome

  • hamido

    Thank you from Morocco,good job

  • Monica

    Thank you for this tutorial. I thought I could start learning Spring doing this example, but for me it does not work. I followed the instructions carefully, but the resulting eclipse project has some error(s). When I run it I get the error

    Could not find or load main class com.mkyong.common.App

    The file App.java now has no errors. In the beginning it had, but after I added the file spring-2.5.6.jar the errors disappeared. I don’t find any file with errors in the whole project SpringExamples.

    What could be the problem? Any help will be greatly appreciated. And by the way, the code provided for download has the same error.

  • madd

    Also getting

    ClassPathXmlApplicationContext cannot be resolved to a type

  • Fareed Mohammed

    it is excellent web site for java developer

  • Arul

    Superb. very nice!!

  • nagappa

    Hi MKYong,
    Most of your tutorials not working for those who are trying in 2013,Please suggest wt to do?.Many people simply wasting the time,

    • praveen

      They are working fine. You might have configuraiton issues with jars , build etc which developer must own responsibality.
      You cannot expect MyKong to spoon feed you with setup , execution …..
      also note that the version of framework keeps changing , you must look into those also.

    • Karthik

      make sure maven is working fine

    • Alvaro Durandal

      I just try this example today and it worked, try harder…

  • http://xenonoutlet.co.uk/ xenon

    I will be interested and enthusiastic about what you’re covering the following.

  • Jack

    Nice Post, thanks mkyong. Got one question though. How does spring know the configuration file is under main/resources? in my local environment, I receives the following exception:
    ==============================
    INFO: Loading XML bean definitions from class path resource [Spring-Moduleg.xml]
    Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [Spring-Moduleg.xml]; nested exception is java.io.FileNotFoundException: class path resource [Spring-Moduleg.xml] cannot be opened because it does not exist
    =====================================

    can you advice please? Thank you.

    • Jack

      please ignore my question. after add the following line in .classpath file, it works like charm.

      &lt;classpathentry including=&quot;**/*.xml&quot; kind=&quot;src&quot; path=&quot;src/main/resources&quot;/&gt;

      thank you

  • http://www.bluelotuz.weebly.com RAJEEV
  • Sumit

    I am facing problem with App.java
    =================================
    Exception in thread “main” java.lang.Error: Unresolved compilation problems:
    ApplicationContext cannot be resolved to a type
    ClassPathXmlApplicationContext cannot be resolved to a type

    at com.mkyong.common.App.main(App.java:8)

    • khan

      add the concerned jars to the build path of the project. It will work

  • Mirza

    U really rockkk…. lovee uuu…!!@

  • Andrew

    Thanks mkyong, your example is very much appreciated!

    Just a suggestion, this example could have been done entirely without involving Eclipse by just mentioning that, to execute the app, you can just use maven at the command line:

    mvn exec:java -Dexec.mainClass=”com.mkyong.common.App”

    I know many people use Eclipse, but it is often instructive to design an example with as few extraneous dependencies as possible.

    Thanks again, really do appreciate the time and effort you put into this :).

    Cheers,
    Andrew

    • http://[email protected] neosky11

      Yes,I agree. Thanks! I was confused how to run

  • lakshmi

    Hi i would like to know the materials for spring and hibernate with maven

  • Tiz

    Hi

    just a question

    how can Maven know where the spring and junit jar (or source) are ?
    which repository is maven looking for to download them from ?

    then will it download jars or source ?

    I don’t have junit, yes manually I can that….. BUT…..no with maven

    Thanks

  • Pingback: Hibernate ? Spring « demonstrate ? blog()

  • dinesh

    Dear Yong,

    I have gone through most of the code snippets in your website. The IOC concept is a very useful one. But i have seen most of the samples contains only the hard coded values of the Objects in the xml file. Then how to assign the values dynamically into the dependencies and then inject them into the Components?

    Can you provide me the sample which performs the same?

    Thanks in Advance
    DineshT

    • Sweety

      when spring container creates the object? on call of getBean() ..what happens in case of singilton /prototype?

  • Manjula

    Really nice …Done a good job !!!

  • sanjeeb

    Nice Example.

  • sanjeeb

    Nice example.Thanks Mr.Yong!!!

  • geofrey

    thanks for the example.

  • sads

    nice example

  • kashif

    I am using Tomcat 7, Apache maven 3 and eclipse Helios

  • kashif

    hi,

    i downloaded the source code and build it in maven as described by you but eclipse is not able to detect the spring dependencies tough they are present in the classpath i am getting compile time error in App.java

    -ClassPathXmlApplicationContext cannot be resolved to a type
    -ApplicationContext cannot be resolved to a type

    pls help

    • serby

      restart the eclipse. It worked for me.

      • meet2

        Hi !!
        I am facing same problem here,restarting the eclipse not working for the same error.

        Exception in thread “main” java.lang.Error: Unresolved compilation problems:
        ApplicationContext cannot be resolved to a type
        ClassPathXmlApplicationContext cannot be resolved to a type

        at com.mkyong.common.App.main(App.java:8)

        • NB

          MkYong, Kindly reply to this problem.. I am also facing the same problem.

          • kavita

            Hi

            I am also facing the same problem please reply for this

          • Asdrubal

            restarting eclipse worked 4 me…

  • Jay prakash

    How to control back button after logout in struts.

  • Krishna Pujara

    Thanks a lot….really helpful…

    • Amit

      nice example…:D

  • http://www.aaadealsite.com Blair Orlens

    Thank you for posting this article.It is very nice and helpful

  • mavenexample

    when i run mvn eclipse:eclipse in cmd .. i see this where shld be the problem ..

    3.HTML –

     [INFO] ------------------------------------------------------------------------
    [INFO] Reactor Summary:
    [INFO]
    [INFO] SpringMVCExamples ................................. SUCCESS [2.313s]
    [INFO] glassfish shaded jar .............................. SUCCESS [6:54.312s]
    [INFO] glassfish web application ......................... SUCCESS [1:27.797s]
    [INFO] SpringMVCExamples-ear assembly .................... FAILURE [5.641s]
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 8:32.203s
    [INFO] Finished at: Fri Mar 02 22:08:50 CST 2012
    [INFO] Final Memory: 8M/21M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal on project SpringMVCExamples-ear: Could not resol
    ve dependencies for project com.sushma.common:SpringMVCExamples-ear:ear:3: Could
     not find artifact com.sushma.common:SpringMVCExamples-web:war:3 in jboss-reposi
    tory (http://repository.jboss.org/nexus/content/groups/public-jboss/) -&gt; [Help 1
    ]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
    ch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please rea
    d the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyReso
    lutionException
    [ERROR]
    [ERROR] After correcting the problems, you can resume the build with the command
     
    [ERROR]   mvn  -rf :SpringMVCExamples-ear
  • Abdennour
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    Eclipse cannot find this two classes .
    NOTE: the previous steps are done successfully .

    • Daniel Lower

      I also had this but solved it by going at least in Eclipse Indigo. Right Click on the Project and do Configure->Convert to Maven project then as if by magic it seemed to load the spring dependencies and bingo the two warnings went away. Admitedly I was experimenting with a fully loaded Maven repository but I suspect it will still work just might take a while do download the depenencies.

      I also added the following to the pom file just below dependencies.

        &lt;build&gt;
        &lt;plugins&gt;  	 
          &lt;plugin&gt;
            &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;
            &lt;configuration&gt;
              &lt;descriptorRefs&gt;
                &lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt;
              &lt;/descriptorRefs&gt;
              &lt;archive&gt;
                &lt;manifest&gt;
                  &lt;mainClass&gt;com.mkyong.core.App&lt;/mainClass&gt;
                &lt;/manifest&gt;
              &lt;/archive&gt;
            &lt;/configuration&gt;
            &lt;executions&gt;
              &lt;execution&gt;
                &lt;phase&gt;package&lt;/phase&gt;
                &lt;goals&gt;
                  &lt;goal&gt;single&lt;/goal&gt;
                &lt;/goals&gt;
              &lt;/execution&gt;
            &lt;/executions&gt;
          &lt;/plugin&gt;  
        &lt;/plugins&gt;
        &lt;/build&gt;

      Then you can go javar -jar Spring3-Example-1.0-SNAPSHOT-jar-with-dependencies.jar
      and then you will have you can run your spring app.

      • Daniel Lower

        Ohh and sorry to compile it I just used maven the command line version and went
        mvn -Dskiptests clean package then the jar file is in the target directory.

        Apart from the couple of missing bits of how to make a good jar and howto run it,
        it is a sweet little tutorial. The output for me looked like this…

        31-Oct-2012 23:05:20 org.springframework.context.support.AbstractApplicationContext prepa
        reRefresh
        INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@19c26
        f5: startup date [Wed Oct 31 23:05:20 GMT 2012]; root of context hierarchy
        31-Oct-2012 23:05:20 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBe
        anDefinitions
        INFO: Loading XML bean definitions from class path resource [SpringBeans.xml]
        31-Oct-2012 23:05:22 org.springframework.beans.factory.support.DefaultListableBeanFactory
        preInstantiateSingletons
        INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultLi
        stableBeanFactory@d251a3: defining beans [helloBean]; root of factory hierarchy
        Spring 3 : Hello ! Mkyong

  • Muskandaza

    Appreciated you efforts , but to get more clarity and understanding please post the tutorials developing in Eclipse IDE .

    • http://www.mkyong.com mkyong

      Don’t get you, this post is developed in Eclipse environment.

      • Muskandaza

        Mkyong @ Best , I regret for confusion ., what i mean is it would be easy if you can post the step by step screen print of the development in eclipse ide .so that every individual can easily follow . What i felt is there are few developer havinf less experience could not follow this tutorial .Though its really excellent and one of the best in Internet ,like the executing the mvn . Appreciate your thoughts on this mvn eclipse:eclipse creates confusion whether it needs to execute in command prompt and which path .Again Many thanks – Muskandaza ,SIU – Carbondale

        • http://www.mkyong.com mkyong

          i see… sorry for the confusion, and thanks for your suggestion, i will improve it continuously.

          • Muskandaza

            MKyong @ Best , Really appreciated for prompt response. I could say one thing your tutorials are really helpful to many people across the globe ,who are enjoying in learning the latest technologies in java . Keep doing good work .Best wishes – Muskandaza,SIU-Carbondale

  • dinesh tiwari

    Very Very good !!
    Well done boy !!

  • Pingback: Maven Spring hello world example - Maven Tutorial()

  • David

    Nice and clear ! Find another one at
    http://www.java-tutorial.ch/spring/maven-and-spring

  • Inshar

    Hi mkyong,
    I’m getting an error, when i enter the command ‘mvn archetype:generate’ in command prompt.

    Please help me.

    C:\>mvn archetype:generate
    [INFO] Scanning for projects…
    [INFO] Searching repository for plugin with prefix: ‘archetype’.
    [INFO] org.apache.maven.plugins: checking for updates from central
    [WARNING] repository metadata for: ‘org.apache.maven.plugins’ could not be retrieved from repository: central due to an error:
    [INFO] Repository ‘central’ will be blacklisted
    [INFO] ————————————————————————
    [ERROR] BUILD ERROR
    [INFO] ————————————————————————
    [INFO] The plugin ‘org.apache.maven.plugins:maven-archetype-plugin’ does not exist or no valid version could be found
    [INFO] ————————————————————————
    [INFO] For more information, run Maven with the -e switch
    [INFO] ————————————————————————
    [INFO] Total time: 21 seconds
    [INFO] Finished at: Tue Apr 19 17:09:47 IST 2011
    [INFO] Final Memory: 1M/4M
    [INFO] ————————————————————————
    ‘cmd’ is not recognized as an internal or external command,
    operable program or batch file.
    C:\>

    • http://www.mkyong.com mkyong

      “Repository ‘central’ will be blacklisted” ? you may behind firewall, try configure Maven to use proxy access.

  • pete

    I don’t understand why you chose vaadin archetype???

    15: remote -> vaadin-archetype-sample (This archetype generates a Vaadin application as a Maven project.
    The application contains a custom GWT widgetset that is compiled
    by the GWT compiler and integrated into the project as part of the
    build process. The application is based on the Vaadin Color Picker
    Demo application available at http://vaadin.com.)

    • http://www.mkyong.com mkyong

      At my end, “15: internal -> maven-archetype-quickstart ()” , what’s your Maven version?

  • http://www.jdbctutorial.net Tousif Khan

    Hi Yong.

    I have maven installed on my machine but when i execute “archetype:generate”
    command it gives the following error. :(

    E:\TestWorkspace>maven archetype:generate
    __ __
    | \/ |__ _Apache__ ___
    | |\/| / _` \ V / -_) ‘ \ ~ intelligent projects ~
    |_| |_\__,_|\_/\___|_||_| v. 1.0.2

    BUILD FAILED
    Goal “archetype:generate” does not exist in this project.
    Total time: 1 seconds
    Finished at: Mon Dec 13 14:16:53 GMT+05:30 2010

    Please Help……

    • http://www.mkyong.com mkyong

      What’s your maven version?

      • http://www.jdbctutorial.net Tousif Khan

        It’s v1.0.2.
        Do i need to update it? or need to install some plug-in over Maven?

  • nextcome

    I think you missed one line of explanation.

    1) go to \\
    here is your pom.xml.

    then run following command from here (otherwise will give you error: POM not found).

    Type “mvn eclipse:eclipse” to convert the newly generated project to Eclipse’s style project..

    Thanks.

    • http://www.mkyong.com mkyong

      Thanks for your extra inputs, really appreciated it.

      • meet2

        I am facing problem with App.java
        =================================
        Exception in thread “main” java.lang.Error: Unresolved compilation problems:
        ApplicationContext cannot be resolved to a type
        ClassPathXmlApplicationContext cannot be resolved to a type

        at com.mkyong.common.App.main(App.java:8)

        Note :- it should automatically download all the dependencies.
        Let me know where i have to change in code ?

  • Suresh

    Thanks a lot Mykong for the nice article !!

  • Yogi

    Very nice , simple and to the point.

  • Pingback: Spring Tutorials | Tutorials()

  • Pingback: Maven Tutorials | Tutorials()

  • Pingback: Maven + Spring + JDBC Example | Spring()