In this section, we'll create a hello world example and set up the Eclipse environment for Spring. You can download the latest Eclipse version from http://www.eclipse.org/downloads/.
Note that Spring provides a specific Eclipse distribution for Spring, known as Spring Tool Suite (STS). STS is customized for developing Spring applications. You can download STS from http://spring.io/tools/sts.
Download the Spring 4.1.0 JAR from the Maven repository at http://search.maven.org/ or http://mvnrepository.com/artifact/org.springframework.
Launch Eclipse and create a Java project and name it
SpringOverview
.Add the following dependencies:
Create a
com.packt.lifecycle
package undersrc
.Add a
HelloWorld
class with following details:public class HelloWorld { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
Add an XML file,
applicationContext.xml
, directly under thesrc
folder and add the bean definition as follows:<?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.xsd"> <bean id="helloWorld" class="com.packt.lifecycle.HelloWorld"> <property name="message" value="Welcome to the Spring world"> </property> </bean> </beans>
Create a Java class,
HelloWorldExample
, and add the following lines to check the bean configuration:public class HelloWorldExample { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); HelloWorld world = (HelloWorld) context.getBean("helloWorld"); System.out.println(world.getMessage()); } }
We load the Spring bean configuration from an XML file, which is kept in the classpath and named
applicationContext.xml
, and then ask the context to find a bean with a name or ID ashelloWorld
. Finally, we call thegetMessage()
method on the bean to check the value we set in the application context.When we run the
HelloWorldExample
program, the following output is displayed: