Spring 3 hello world example

This tutorial shows you how to create a simple hello world example in Spring 3.0.

Technologies used in this article :

  1. Spring 3.0.5.RELEASE
  2. Maven 3.0.3
  3. Eclipse 3.6
  4. JDK 1.6.0.13

P.S Spring 3.0, at least JDK 1.5 is required to work.

Spring 3.0 dependencies
In Spring 2.5.x, almost the entire Spring modules are grouped into a single spring.jar file. Since Spring 3.0, every modules are split into an individual jar file, for example, spring-core, spring-expression, spring-context, spring-aop and etc, for detail , please refer to this article – Obtaining Spring 3 Artifacts with Maven.

1. Generate project structure with Maven

Issue below Maven command to create a standard Java project structure.


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

2. Convert to Eclipse project

Convert Maven style project to Eclipse’s style project, and import into Eclipse IDE.


mvn eclipse:eclipse

2. Add Spring 3.0 dependency

Add the Spring 3.0 dependencies listed below in Maven’s pom.xml file. The Spring dependencies are available for download via Maven central repository.

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.core</groupId>
	<artifactId>Spring3Example</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>Spring3Example</name>
	<url>http://maven.apache.org</url>

	<properties>
		<spring.version>3.0.5.RELEASE</spring.version>
	</properties>

	<dependencies>

		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

	</dependencies>
</project>

3. Spring bean

A simple Spring bean.


package com.mkyong.core;

/**
 * Spring bean
 * 
 */
public class HelloWorld {
	private String name;

	public void setName(String name) {
		this.name = name;
	}

	public void printHello() {
		System.out.println("Spring 3 : Hello ! " + name);
	}
}

4. Spring bean configuration file

Create a Spring configuration file, and declare all the available Spring beans.

File : SpringBeans.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-3.0.xsd">

	<bean id="helloBean" class="com.mkyong.core.HelloWorld">
		<property name="name" value="Mkyong" />
	</bean>

</beans>

5. Review project structure

Review directory structure as follows

spring3 hello world example

6. Run It

Run it.


package com.mkyong.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"SpringBeans.xml");

		HelloWorld obj = (HelloWorld) context.getBean("helloBean");
		obj.printHello();
	}
}

7. Output


Spring 3 : Hello ! Mkyong

Download Source Code

Download it – Spring3-hello-world-example.zip (5KB)
Try JavaConfig annotation
This may interest you Spring 3 hello world example using JavaConfig annotation.

References

  1. Spring 3 artifacts with Maven/

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
47 Comment threads
25 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
51 Comment authors
saroj kumar dasJason RembertshareefRanjit MandavalliDavid Kingsbury Recent comment authors
newest oldest most voted
Jason Rembert
Guest
Jason Rembert

If you dont want to set up a Maven project. Use this tool to download the jar files: http://jar-download.com/

shareef
Guest
shareef

to solve problem of missing dependencies

java.net

http://download.java.net/maven/2/

Ignatius Damai
Guest
Ignatius Damai

Hi,

I am new to Spring and Maven. I have a problem when I’m importing my project to eclipse.
When I do everything manually, and run “mvn install” in the end, my eclipse returned:

Exception in thread “main” java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextCaused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContext
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

When I try to load the provided source code, I got:

Error: Could not find or load main class com.mkyong.core.App

Am I missing a plugin, or do I need to downgrade my JDK 7u45 for this tutorial to JDK 6? Thank you so much!

Adrian
Guest
Adrian

I am getting the same problem as well and I dunno how to fix it =[. Someone please help. I try to run it from command prompt with

java -cp target/Spring3Example-1.0-SNAPSHOT.jar com.mkyong.core

but it says it could not find main class com.mkyong.core

David Kingsbury
Guest
David Kingsbury

For anyone having problems running this: replace the POM with this updated POM: http://pastebin.com/T6B8ZiYh (it uses the Maven Shade plugin for packaging)

shivakumar
Guest
shivakumar

Hi mkyong; I m getting an exception as SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. [INFO] Scanning for projects… [INFO] [INFO] ———————————————————————— [INFO] Building DemoMVC 0.0.1-SNAPSHOT [INFO] ———————————————————————— [INFO] [INFO] — maven-resources-plugin:2.5:resources (default-resources) @ DemoMVC — [debug] execute contextualize [INFO] Using ‘UTF-8’ encoding to copy filtered resources. [INFO] Copying 2 resources [INFO] [INFO] — maven-compiler-plugin:2.3.2:compile (default-compile) @ DemoMVC — [INFO] Compiling 1 source file to C:UsersSHIVUworkspaceDemoMVCtargetclasses [INFO] ————————————————————- [ERROR] COMPILATION ERROR : [INFO] ————————————————————- [ERROR] Unable to locate the Javac Compiler in: C:Program FilesJavajre7..libtools.jar Please ensure you are… Read more »

archi
Guest
archi

hii…can anyone tell me how to merge the 2 or more class using tha dependency .

archi
Guest
archi

pls reply asap ..

Johaness
Guest
Johaness

I think its ridiculous forcing use of maven to build a hello world project. The main theme is not maven but SPRING. Think about the inexperienced people! Damn

PosTi85
Guest
PosTi85

It worked like a charm. Thank you for such a clear example.

Madhan Ganesh
Guest
Madhan Ganesh

Thanks mkyong! This is really useful and a quick start for newbie like me. Keep up the good work.

Monica
Guest
Monica

I can’t get it work. I even tried to use the source code provided by Mkyong. It already shows there is an error in the project, and when I ran it I got the error:

Error: Could not find or load main class com.mkyong.core.App

I added the folder Spring3Example/src/main/java/com/mkyong/core to the Libraries in the Java build path, but it does not help.

Any idea about what to do? What am I missing?

Emmanuel
Guest
Emmanuel

I get this error when I run.

Exception in thread “main” java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext
Caused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContext
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

Thanks.

Tamilarasan Subramaniam
Guest
Tamilarasan Subramaniam

Im also getting same error. while i have followed as mentioned in the way

Paul Nevill
Guest
Paul Nevill

After struggling with this for awhile I got it working by doing the following: -Set you dependencies in pom.xml to work with Spring 3 this way: 3.0.5.RELEASE org.springframework spring-core ${org.springframework.version} org.springframework spring-beans ${org.springframework.version} org.springframework spring-context ${org.springframework.version} (not sure why this worked for me and the tutorials version didn’t) -Issue command “mvn install” after first command in tutorial (might not be necessary?) -Set your eclipse M2_REPO to your maven repository. Project > Preferences > Java > Build Path > Classpath Variables > New For me it was C:\Users\\.m2\repository -Also, because it isn’t a part of this tutorial, be sure to properly… Read more »

codewarrior
Guest
codewarrior

Thank you Paul. Your post helped a lot in getting the Project to work.

Tamilarasan Subramaniam
Guest
Tamilarasan Subramaniam

Thanks a lot Mr Paul. It’s working fine after as you mentioned step followed. Great men…..

Himanshu Verma
Guest
Himanshu Verma

Hi Yong,

I got below error when i issued the command

D:\spring example\Spring3-hello-world-example\Spring3Example>mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=Spring3Example -DarchetypeArtifa
ctId=maven-archetype-quickstart -DinteractiveMode=false
[INFO] Scanning for projects…
[INFO]
[INFO] ————————————————————————
[INFO] Building Spring3Example 1.0-SNAPSHOT
[INFO] ————————————————————————
[INFO]
[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ Spring3Example >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ Spring3Example << [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[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 read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Motlanthe
Guest
Motlanthe

Hi, your tutorials are awesome – keep it up :) I happened to get errors in this tutorial though in the main method:
Unhandled exception org.springframework.beans.BeansException. It appears in the App class:

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloBean");

I tried adding the exception to the signature and also tried a try catch but that didn’t help. Further info:
java: cannot access org.springframework.core.io.DefaultResourceLoader class file for org.springframework.core.io.DefaultResourceLoader not found
and
java: cannot access org.springframework.core.io.support.ResourcePatternResolver class file for org.springframework.core.io.support.ResourcePatternResolver not found

Any ideas? thanks in advance

tom
Guest
tom

Hi Yong,

I got the below error when i run the first command.

C:\Spring3Example>mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=Spring3Example -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

[ERROR] No plugin found for prefix ‘archetype’ in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\repository), central (http://repo1.maven.org/maven2)] -> [Help 1]

TEST
Guest
TEST

For newest information you have to go to see world-wide-web
and on web I found this web site as a best web site for most up-to-date
updates.

rajeev
Guest
rajeev

YOu forgot to mention that after Maven download of SpringExample, one has to change the directory…to..Spring3Example

Srikanth
Guest
Srikanth

What is the difference between Maven + Spring Hello World Example & the spring 3.0 example?

Gireesh Kumar
Guest
Gireesh Kumar

Hi mkyong,

Great starting point for a Spring learning student. Expecting more posts in spring 3.

DucNguyen
Guest
DucNguyen

Sorry for my naive question .

I have run packge in Eclipse successful.

but I don’t know how to run it’s in Eclispe.

This mean I can’t get step 7’th of your tutorial.

sorry for my bad english

Kevin
Guest
Kevin

If your file structure is the same as mentioned in step 5, right click the App.java file in Project Explorer (in eclipse) and select “Run As” and select “Java Application.

trackback
A Tale of Two Web Stacks: Java vs .NET | DaedTech

[…] find another blog post and learn that the “properties” tag needs to go outside of the […]

fxcrypto
Guest
fxcrypto

git this to work quickly and smoothly thanks so much, just to help

1. step 1 if u cut paste html can be problems with ‘-‘ chars
2. compiled mvn eclipse imported to eclipse, set up pom, exited eclipse compiled mvn eclipse
3. some classpath problems, exited eclipse repeat compiled mvn eclipse

fixed, now have spring again many thanks

Ranjeet
Guest
Ranjeet

How I can build this hello world example on NetBeans [Using 7.1.2].

Sarfraz
Guest
Sarfraz

Nice tutorial! It just simple ans straight

trackback
Spring 3 MVC hello world example

[…] Spring 3 hello world example […]

trackback
Creating a spring 3 maven project « Ruel's Blog

[…] http://www.mkyong.com/spring3/spring-3-hello-world-example/ Like this:LikeBe the first to like this. […]

Jaya
Guest
Jaya

Hi,
Could you please explain a JSF+Spring+Hibernate project without using Maven dependencies?

Ankush
Guest
Ankush

HI.. sir I am Ankush.. I just downloded Hello spring+maven application.. I imported that application in MyEclipse.. While building application I got following error.. Please Help me out sir as soon as possible.. [INFO] ———————————————————————— [INFO] BUILD FAILURE [INFO] ———————————————————————— [INFO] Total time: 5:45.473s [INFO] Finished at: Mon Jul 16 14:32:29 IST 2012 [INFO] Final Memory: 2M/5M [INFO] ———————————————————————— [ERROR] Failed to execute goal on project Spring3Example: Could not resolve dependencies for project com.mkyong.core:Spring3Example:jar:1.0-SNAPSHOT: Could not transfer artifact org.springframework:spring-core:jar:3.0.5.RELEASE from/to central (http://repo1.maven.org/maven2): No response received after 60000 -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the… Read more »

Ankit
Guest
Ankit

Try using 3.0.5 instead of 3.0.5.RELEASE in the Properties section.

Beniton
Guest
Beniton

Wow Super

Cam
Guest
Cam

Mkyong,

You should reverse the order of your “Step 2” instructions. The “mvn eclipse:eclipse” command should be run after the dependencies are added, since the classpath and project files will need to be rebuilt.

Cam
Guest
Cam

Side note, if you’re wanting to add the dependencies through Eclipse IDE, you’ll need to do the “mvn eclipse:eclipse” command before and after adding the dependencies since you won’t be able to import the project before it has a .project file.

Steve
Guest
Steve

I downloaded the project example, clean and install with maven works fine but when I run the project I got the following errors, please help:
Caused by: java.lang.ClassNotFoundException: com.example.core.App
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

Also, as I understand, the pom declares dependances and maven will automatically download the required jar files. I followed the URL of the pom and the newest version of spring from that URL is 3.1.1 while the current version is 3.2.0. How can I make it work with3.2.0? Thanks