Beans

Spring 3 Hello World Example

This is an example of how to create a simple Hello World Bean in Spring 3.2.3. The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications – on any kind of deployment platform.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using Spring version 3.2.3 and the JDK 7_u_21.

Let’s begin.

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New-Maven-Project

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.

Maven-Project-Name-Location

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Hit “Finish” to exit the wizard and to create your project.

Configure-Maven-Project

The Maven project structure is shown below:

Maven-project-structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring 3.2.3 dependency

  • Locate the “Properties” section at the “Overview” page of the POM editor and perform the following changes:
    Create a new property with name org.springframework.version and value 3.2.3.RELEASE.
  • Navigate to the “Dependencies” page of the POM editor and create the following dependencies (you should fill the “GroupId”, “Artifact Id” and “Version” fields of the “Dependency Details” section at that page):
    Group Id : org.springframework Artifact Id : spring-web Version : ${org.springframework.version}

Alternatively, you can add the Spring dependencies in Maven’s pom.xml file, by directly editing it at the “Pom.xml” page of the POM editor, as shown below:

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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>springexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

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

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>
</project>

As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.

3. Create the Spring bean configuration file

Now let’s create the applicationContext.xml file that will drive Spring container. Create the file under /src/main/resources directory. An example "applicationContext.xml" is presented below:

applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<context:component-scan base-package="com.javacodegeeks.snippets.enterprise" />

</beans>

Something important to notice here is that you should change the base-package attribute of the context:component-scan element to whatever is the base package of your project so as to be scanned for Spring components e.g service components annotated with @Service annotation.

4. Create a Spring bean

Let’s create now a "helloWorld” Spring service. Create a sub–package named "services” under your main package and place the "HelloWorldService” class there. An example "helloWorldService” is shown below:

HelloWorldService.java:

package com.javacodegeeks.snippets.enterprise.services;


import org.springframework.stereotype.Service;

@Service("helloWorldService")
public class HelloWorldService {
	
	private String name;

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

	public String sayHello() {
		return "Hello from HelloWorld Service! " + name;
	}

}

We use the @Service("helloWorldService”) stereotype annotation so as to declare that this class represents a Spring service by the name "helloWorldService”. The Spring container will instantiate all services at start up.

Alternatively, we can declare the Spring bean directly to the "applicationContext.xml" file by omitting the @Service("helloWorldService”) stereotype annotation from the bean class, removing the context:component-scan element from the "applicationContext.xml" file and adding to it the Sping bean declaration that is shown below:

applicationContext.xml:

	<bean id="helloWorldService" class="com.javacodegeeks.snippets.enterprise.services.HelloWorldService">
		<property name="name" value="Spring 3.2.3" />
	</bean>

5. Run the project with Maven

In the App Class, we create an ApplicationContext object, that loads the applicationContext.xm file. We can use the ApplicationContext object to get an instance of any specified Spring Bean, when it is annotated with @Service annotation, or when it is declared as a Spring bean in the applicationContext.xml file.

App.java:

package com.javacodegeeks.snippets.enterprise;


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

import com.javacodegeeks.snippets.enterprise.services.HelloWorldService;


public class App {
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {

	/**
	 * Create a new ApplicationContext, loading the 
	 * definitions from the given XML file 
	 */
	ApplicationContext context = new ClassPathXmlApplicationContext(
			"applicationContext.xml");
	/**
	 * Return an instance, which may be shared or 
	 * independent, of the specified bean.
	 */
	HelloWorldService obj = (HelloWorldService) context.getBean("helloWorldService");
	obj.setName("Spring 3.2.3");
	String message =obj.sayHello();
	System.out.println(message);
	}
}

In order to run the application Rignt click on the App class -> Choose Run As -> Java Application :

Run-the-application

6. Output

When you execute the application you should see something like the output presented below:

Hello from HelloWorld Service! Spring 3.2.3

 
This was an example of how to create a simple Hello World Bean using Spring 3.2.3 in Java.

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button