Spring 3 hello world in Eclipse

Spring 3 hello world in Eclipse

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

Technologies used :

  1. Spring 3.0.5.RELEASE
  2. Maven
  3. Eclipse
  4. JDK 1.5 or higher

1) Create maven project in Eclipse.

2) Add Spring 3.0 dependency

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.code2succeed.core</groupId>
  <artifactId>springcore</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springcore</name>
  <description>springcore</description>
  
  <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 (HelloWorld.java file)

package com.code2succeed.core;

public class HelloWorld {
  private String name;

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

  public void printName() {
    System.out.println("Hello "+name);
  }
}

4) Spring Configuration file

beans.xml file

<?xml version="1.0" encoding="UTF-8"?>
<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.code2succeed.core.HelloWorld">
		<property name="name" value="Code2Succeed" />
	</bean>

</beans>

5) Folder Structure of the project.

spring-helloworld-folder-structure

6) Run App.java file.

package com.code2succeed.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("beans.xml");

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

}

7) Output

Hello Code2Succeed

Leave a Reply

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