Book Image

Mockito for Spring

By : Sujoy Acharya
Book Image

Mockito for Spring

By: Sujoy Acharya

Overview of this book

Table of Contents (12 chapters)
Mockito for Spring
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Printing Hello World


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.

  1. Launch Eclipse and create a Java project and name it SpringOverview.

  2. Add the following dependencies:

  3. Create a com.packt.lifecycle package under src.

  4. 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;
      }
    }
  5. Add an XML file, applicationContext.xml, directly under the src 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>
  6. 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 as helloWorld. Finally, we call the getMessage() method on the bean to check the value we set in the application context.

  7. When we run the HelloWorldExample program, the following output is displayed: