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)

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Nguy?n Duy Phong
Guest
Nguy?n Duy Phong

Thanks you very much!

PatcharapholP
Guest
PatcharapholP

how can i convert to IntelliJ styles ?
I have try it but there is some problem with mvn idea:module that get ERROR Failed to execute goal org.apache.maven.plugins:maven-idea-plugin:2.2.1:module on project …….. : Execution default-cli of goal org.apache.maven.plugins:maven-idea-plugin:2.2.1:module failed. : NullPointerException

Segen01
Guest
Segen01

ffs….no…..maven!!!!!!

vishnu ts
Guest
vishnu ts

Hi mkyong, Thanks for this article. I did everything like you described here expect I used the Spring latest version. But I am getting error like’ClassPathXmlApplicationContext and ApplicationContext are not available’. What I understood is Spring dependency jar “spring 4.2.0” not available.But I checked the class path, jar is available there.

Can anybody please look into this!!! help me……..

VenkatBharath
Guest
VenkatBharath

Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘helloBean’ defined in class path resource [bean.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.mkyong.common.HelloWorld]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.mkyong.common.HelloWorld.()

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:883)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)

at java.security.AccessController.doPrivileged(Native Method)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)

at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)

at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)

at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)

at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)

at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)

at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)

at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)

at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)

at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)

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

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.mkyong.common.HelloWorld]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.mkyong.common.HelloWorld.()

at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:58)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)

… 16 more

Caused by: java.lang.NoSuchMethodException: com.mkyong.common.HelloWorld.()

at java.lang.Class.getConstructor0(Class.java:2892)

at java.lang.Class.getDeclaredConstructor(Class.java:2058)

at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:54)

… 17 more

süleyman ?ahin
Guest
süleyman ?ahin

i got same error. Did you solve problem ?

yeswanth g
Guest
yeswanth g

Please Specify Bean Path correctly or class path correctly in spring-module.xml file

Sai Kumar Pabboju
Guest
Sai Kumar Pabboju

can you please paste the code here!

Java Pro
Guest
Java Pro
Rômulo Sorato
Guest
Rômulo Sorato

Hi i´m trying to compile the App.java
but when i run I get the error

Could not find or load main class com.mkyong.common.App
already have im my POM the dependencies for commons annotations so
what can be the problem?
There´s no error in the project.
Thanks.

Helper
Guest
Helper

Just right click on your project then run as and click on maven install after doing this try to run your App.java , It’ll compile and run easily.

prateek agrawal
Guest
prateek agrawal

i am getting error in first step itself. when i write the command i get the following lines in the end.
Please help me.

Choose a number or apply filter (format: [groupId:]artifactId, case sensitive co

ntains): 387: -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMo

de=false

Choose archetype:

Your filter doesn’t match any archetype (hint: enter to return to initial lis

t)

Spring learner
Guest
Spring learner

Great work perfectly.. :D thanks..

Zahid
Guest
Zahid

Please help me I am new to Maven I cant understand the configurations of using Sping.

trackback
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,

[…] I am new to maven and trying to run simple spring demo. I am using Intellij IDEA as my IDE. I am following tutorial provided here. […]

balkrushn
Guest
balkrushn

I am getting Error:

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

Please Help Me. I am new to maven

Mayank jaiswal
Guest
Mayank jaiswal

The program is running fine I need to create this program using Eclipse editor. I already install this springtoolssuit

trackback
Maven | indybee83

[…] Maven plus Spring […]

Cody
Guest
Cody

Thanks, Mkyong. You’re awesome

hamido
Guest
hamido

Thank you from Morocco,good job

Monica
Guest
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,… Read more »
Mani Jana
Guest
Mani Jana

This is caused by the missing of commons-logging-xxx.jar

If you want more information please refer this link :
http://www.mkyong.com/java/javalangnoclassdeffounderror-orgapachecommonslogginglogfactory/

madd
Guest
madd

Also getting

ClassPathXmlApplicationContext cannot be resolved to a type

yuvaraj
Guest
yuvaraj

Add spring-context jar to rectify this…

Fareed Mohammed
Guest
Fareed Mohammed

it is excellent web site for java developer

Arul
Guest
Arul

Superb. very nice!!

nagappa
Guest
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
Guest
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
Guest
Karthik

make sure maven is working fine

Alvaro Durandal
Guest
Alvaro Durandal

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

xenon
Guest
xenon

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

Jack
Guest
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
Guest
Jack

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

<classpathentry including="**/*.xml" kind="src" path="src/main/resources"/>

thank you

rohitnsit08
Guest
rohitnsit08

Hi Jack, I think as a good habit, one should avoid changing .classpath file manually. For your exception you only needed to run mvn eclipse:eclipse once and refresh your project in eclipse.

RAJEEV
Guest
RAJEEV

hi mkyong..
am new to java and am so addicted to java.
I uv learned upto making applets and connecting with oracle,sql databases..
now I want to knw ant way is spring,hibernate and so..
pls say any idea to understand easily..
my mail id is : mailto.rajiv18@yahoo.com

Sumit
Guest
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
Guest
khan

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

Mirza
Guest
Mirza

U really rockkk…. lovee uuu…!!@

Andrew
Guest
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

neosky11
Guest
neosky11

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

lakshmi
Guest
lakshmi

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

Tiz
Guest
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

trackback
Hibernate ? Spring « demonstrate ? blog

[…] spring ?????????????????????????? spring framework ?????????? IoC container […]