How To Create Spring 4.3 Hello World Application With Maven

In the previous article we saw how to create Hello World Spring 4.3  Java application.  In this tutorial let us see how to create a hello world Java application with Maven.  In the last example we had to manually download the Spring jars and attach it to the project.  However making sure all the dependencies are present is a big problem.  Here is where Maven can help us.

Prerequisites – Your computer should have maven installed.

Steps

Create Maven Archetype project with Eclipse Maven plugin.

File > New > Maven Project

The below window should appear.  Select Next.

mavenproj1

In the pop up select maven-archetype-quickstart and click Next
mavenproj2

In the next screen select Group id as com.freetipscentral and Artifact id as HelloWorld and click Finish.  You will see that a project is created with the name HelloWorld.

maven proj 3

Open the HelloWorld.  There will be a pom.xml  file.  Open the file and add the following dependency.

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.freetipscentral</groupId>
  <artifactId>HelloWorld</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>HelloWorld</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>


  </dependencies>
</project>

As soon as you save the file maven dependencies will be downloaded.  You will see the following dependencies

workspace structure

The App.java is generated automatically.  However you need the following files.

HelloWorld.java

package com.freetipscentral.HelloWorld;

public class HelloWorld {
  public void sayHello(){
    System.out.println("Hello World");
  }
}

TestHelloWorld.java

package com.freetipscentral.HelloWorld;

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

public class TestHelloWorld {
  public static void main(String args[]){
    // create and configure beans
    ApplicationContext context =
        new ClassPathXmlApplicationContext("config.xml");
    // retrieve configured instance
    HelloWorld firstBean = (HelloWorld)context.getBean("helloWorld");
    firstBean.sayHello();
  }
}

config.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-4.3.xsd">
  <bean class="com.freetipscentral.HelloWorld.HelloWorld" id="helloWorld">
  </bean>
</beans>

When you run TestHelloWorld.java you get the following output

 

Sep 16, 2016 10:03:59 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4d405ef7: startup date [Fri Sep 16 22:03:59 CDT 2016]; root of context hierarchy
Sep 16, 2016 10:03:59 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config.xml]
Hello World

Creating a Hello World program in Spring 4.3 with Eclipse

Perfection is not attainable, but if we chase perfection we can catch excellence. ~ Vince Lombardi

Hello World programs are usually the first steps in learning any new technology. Though the programs are simple are rarely do anything significant, they are important from two angles.

a) Your IDE becomes ready for more complex programs because of the setup/configuration you need to perform before you are able to run the Hello World program.

b) It gives you a real feel of though minuscule, how the technology works.

Thus it is important that you create a small program and execute it once you gain the preliminary knowledge of any Technology.  Here is a simple program and steps for how to set it up.  The IDE I have used for this example is Eclipse which is one of the most popular IDEs.

The preferred way is to go for Maven or Gradle.  However for this tutorial I will show how to do the setup with the distribution directly.

Before you start remember to download Spring and unzip it in a directory.  You can download spring framework from https://projects.spring.io/spring-framework/.  Select the version and download the distribution.  Usually you can go for the latest build.

Step 1 : Create a Java Project.

  • Click the following : File NewJava Project
  • In the project name mention “SpringTest”. Click Next
  • Click the Libraries Tab. Click “Add External Jars” button.
  • Now the file browser go to the directory where Spring jars are present. Usually it is “lib” directory under the spring unzip directory. Though you may not need to add all the jar for a hello world program, they will be useful when you create more complex examples using the more advanced features of Spring.  Just select the “RELEASE” versions.
  • You also need commons-logging-1.2.jar. You can download them from  https://commons.apache.org/proper/commons-logging/download_logging.cgi

Step 2 : Create the Files

a) Under the src create a file : “config.xml”.  Here is the content.

<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-4.3.xsd">
 <bean class="com.freetipscentral.HelloWorld" id="helloWorld">
 </bean>
</beans>

This xml file is the Spring configuration file which our application will use.  We declare a bean with id “helloWorld” which refers to HelloWorld class.

b) Create a package.  Right click on src folder and select New > Package .  Name it “com.freetipscentral

c) Create a Java file and name it as “HelloWorld.java” under the “com.freetipscentral” package.  This is a simple java file with just one method sayHello(). Here is the code.

package com.freetipscentral;

public class HelloWorld {
 public void sayHello(){
 System.out.println("Hello World");
 }
}

 

d) Create another Java file “TestHelloWorld.java” under the “com.freetipscentral” package.  This file contains main method.  In the method load we first load the configuration file which create the bean container.  Next, we just access the bean from the container and call the sayHello method.  Here is the code for that.

package com.freetipscentral;

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

public class TestHelloWorld {
 public static void main(String args[]){
 // create and configure beans
 ApplicationContext context =
 new ClassPathXmlApplicationContext("config.xml");
 // retrieve configured instance
 HelloWorld firstBean = (HelloWorld)context.getBean("helloWorld");
 firstBean.sayHello();
 }
}

Step 3 : Run the Example
This is the simplest step. Right click on “TestHelloWorld.java” > Run As > Java Application. You should see the following output.

INFO: Loading XML bean definitions from class path resource [config.xml]
Hello World

Spring MVC Hello World Example

Here are the steps to run a MVC Hello world example in Eclipse.
In spring the request should be passed through Dispatcher servlet which is part of Spring API. This servlet is provided by Spring directly and we just need to map the url to this servlet. When a request is receive by the Spring enabled application, it is received by the Dispatcher Servlet. Dispatcher Servlet looks for the appropriate controller and the view for the request in the configuration file. The request is then sent to Controller which processes the business logic and forwards the request to the appropriate view.

It is important to have all the required files (jars, tld, xml) otherwise you will face numerous issues. I learnt the hard way about the files required for this example hence I am showing the workspace snap which will help you to have all the required files.

In the lib folder copy the jar files shown here. In the WEB-INF directory the tlds are required for jstl, though in this example c.tld is the only one used. So other tld files are optional.

There is another file springmvc-servlet.xml. This file is the spring configuration file which spring uses to determine the controller and view for serving a request. The name of the file is significant here. springmvc should be same as the springmvc which is mentioned for declaring the servlet in the web.xml file.

1. HelloWorldController.java
This file is the controller for the hello-world.html resource. This is a virtual resource in the sense this file does not exists. The controller maps the spring configuration maps it to /jsp/hello_world.jsp

package headfirstspring.controller;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
 
public class HelloWorldController implements Controller {
 
  public ModelAndView handleRequest(HttpServletRequest request,
          HttpServletResponse response) throws ServletException, IOException {
 
      ModelAndView modelAndView = new ModelAndView("hello_world");
      return modelAndView;
  }
}

 

2. DisplayDetailsController.java
This controller intercepts the request when user submits the form in first page (hello_world.jsp) and creates a message object and attaches it to the view.

package headfirstspring.controller;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
 
public class DisplayDetailsController implements Controller {
 
  public ModelAndView handleRequest(HttpServletRequest request,
          HttpServletResponse response) throws ServletException, IOException {
 
      String name = request.getParameter("name");
      String aMessage = "Hello "+name;
 
      ModelAndView modelAndView = new ModelAndView("display_details");
      modelAndView.addObject("message", aMessage);
 
      return modelAndView;
  }
}

 

3. hello-world.jsp
This is the initial jsp and shows the form where in user types in a name and submits it.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
 
  <form action="http://localhost:8080/SpringValidaton/display_details.do" method="post">
      Name : <input name="name" type="text">
      <input value="Submit" type="submit">
  </form>

 

4. display_details.jsp

This jsp shows the welcome message with name of the person submitted from the previous jsp.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
 
      <p>Hello <c:out value="${message} "> Welcome to Spring</c:out></p>

 

 

5. springmvc-servlet.xml
This is the spring configuration file. This file declares the various controllers. In the view declaration notice how the resource is prefixed with /jsp and suffixed with .jsp.

For example if the resource is hello_world it will become /jsp/hello_world.jsp

<beans xmlns="http://www.springframework.org/schema/beans" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean name="/hello_world.html" class="headfirstspring.controller.HelloWorldController">
<bean name="/display_details.do" class="headfirstspring.controller.DisplayDetailsController">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView">
    <property name="prefix" value="/jsp/">
    <property name="suffix" value=".jsp">
</property>
</property>
</property></bean></bean></bean></beans>

 

6. web.xml

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://java.sun.com/xml/ns/j2ee          http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
<servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.html</url-pattern>
</servlet-mapping>
 
<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>
 
<welcome-file-list>
  <welcome-file>
    jsp/index.jsp
  </welcome-file>
</welcome-file-list>
 
<jsp-config>
    <taglib>
      <taglib-uri>http://java.sun.com/jsp/jstl/fmt</taglib-uri>
      <taglib-location>/WEB-INF/fmt.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
      <taglib-location>/WEB-INF/c.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>http://java.sun.com/jsp/jstl/sql</taglib-uri>
      <taglib-location>/WEB-INF/sql.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>http://java.sun.com/jsp/jstl/x</taglib-uri>
      <taglib-location>/WEB-INF/x.tld</taglib-location>
    </taglib>
</jsp-config>
</web-app>

 

Now You can Run the Application after deploying it on Tomcat Server.

 

Here is what should be the response.

 

Spring Lookup Method Injection Example

Just imagine a situation where in you have a Singleton Bean A (In Spring Singleton means exactly one bean per container) and that bean is dependent on another bean B which you do not want to be singleton (Prototype – Multiple copies of the bean can exist for the bean in the container).

In case of Singleton beans, it is initialized only once therefore the dependency bean is also initialized only once though the scope may be Prototype. To solve the problem Spring provides a solution where in the look-up for the dependency bean B is done dynamically and each time container would return a new instance of bean B.

In this example I will first show what happens when we do not use the look up feature and then we have a look at what happens when we use the look-up feature.

Scenario is like this:

We have a Physiotherapist class which can enroll Patients. Imagine that we can only have a single Physiotherapist he can have multiple patients, therefore we have limited the scope of Physiotherapist to singleton. Patient class has Prototype scope which means that it can have multiple instances.

When we do not use the method lookup injection the Patient instance which is initially injected to the singleton class stays and new instance of Patient class is not created since this dependency injection takes place only once during the creation of Physiotherapist class.

Here is the Patient Class. We assign a patient number randomly and that will be used to verify if the instance of the patient class is same or different.

package springbeansamples;
/**
 * @author nilendu.bhattacharya
 *
 */
public class Patient {
 String patientNumber = Integer.toString((int) (Math.random()*100000));
 /**
  * @return Returns the type.
  */
 public String getPatientNumber() {
  return patientNumber;
 }
}
Here is the Physiotherapist Class.
package springbeansamples;
/**
 * @author nilendu.bhattacharya
 */
public class Physiotherapist {
 Patient patient;
 /**
  * @return Returns the patient.
  */
 public Patient getPatient() {
  returnpatient;
 }
 /**
  * @param patient The patient to set.
  */
 public void setPatient(Patient patient) {
  this.patient = patient;
 }
 
 public void showPatientDetails(){
  Patient patient = enrolPatient();
//   Show the patient number of (hopefully brand new) new Patient instance
  System.out.println("New Patient Number is : "+patient.getPatientNumber());
 }
 
 public Patient enrolPatient(){
  return getPatient();
 }
}
This is the entry in the configuration file for the beans.
<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="patient"class="springbeansamples.Patient"scope="prototype">
<!-- inject dependencies here as required -->
</bean>
 <bean id="physiotherapist"class="springbeansamples.Physiotherapist">
 <property name="patient"ref="patient">
  </property>
</bean>
This the result. Notice that same patient instance is there the Physiotherapist instance.
May 21, 2010 3:50:56 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringTest.xml]
New Patient Number is : 34271
New Patient Number is : 34271

Here is the changed Physiotherapist class.
packagespringbeansamples;
/**
 * @author nilendu.bhattacharya
 */
publicabstractclassPhysiotherapist {
 Patient patient;
 /**
  * @return Returns the patient.
  */
 publicPatient getPatient() {
  returnpatient;
 }
 /**
  * @param patient The patient to set.
  */
 publicvoidsetPatient(Patient patient) {
  this.patient = patient;
 }
 
 publicvoidshowPatientDetails(){
  Patient patient = enrolPatient();
//   Show the patient number of (hopefully brand new) new Patient instance
  System.out.println("New Patient Number is : "+patient.getPatientNumber());
 }
 //This is where the lookup injection will take place.  This is abstract method.
 publicabstractPatient enrolPatient();
}
Bean configuration in the Spring configuration file for method lookup injection. Notice that in the bean physiotherapist we have reference to lookup-method
<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="patient"class="springbeansamples.Patient"scope="prototype">
<!-- inject dependencies here as required -->
</bean>
<bean id="physiotherapist"class="springbeansamples.Physiotherapist">
 <lookup-method name="enrolPatient"bean="patient">
</lookup-method></bean>
Here is the output which show how New instance of Patient is generated.
May 21, 2010 3:54:34 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringTest.xml]
New Patient Number is : 51362
New Patient Number is : 3906

Below is the MethodInjectionTest code. Use this class to test if new instance is created for the Patient class.

package springbeansamples;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
 
/**
 * @author nilendu.bhattacharya
 *
 */

public class MethodInjectionTest {
 public static void main(String[] args) {
  XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("SpringTest.xml"));
   
  Physiotherapist physiotherapist = (Physiotherapist) beanFactory.getBean("physiotherapist");
  physiotherapist.showPatientDetails();
  physiotherapist = (Physiotherapist) beanFactory.getBean("physiotherapist");
  physiotherapist.showPatientDetails();
   
 }
}

What Is Dependency Injection

Just imagine a situation where in you have a Singleton Bean A (In Spring Singleton means exactly one bean per container) and that bean is dependent on another bean B which you do not want to be singleton (Prototype – Multiple copies of the bean can exist for the bean in the container).

In case of Singleton beans, it is initialized only once therefore the dependency bean is also initialized only once though the scope may be Prototype. To solve the problem Spring provides a solution where in the look-up for the dependency bean B is done dynamically and each time container would return a new instance of bean B.

In this example I will first show what happens when we do not use the look up feature and then we have a look at what happens when we use the look-up feature.

Scenario is like this:

We have a Physiotherapist class which can enroll Patients. Imagine that we can only have a single Physiotherapist he can have multiple patients, therefore we have limited the scope of Physiotherapist to singleton. Patient class has Prototype scope which means that it can have multiple instances.

When we do not use the method lookup injection the Patient instance which is initially injected to the singleton class stays and new instance of Patient class is not created since this dependency injection takes place only once during the creation of Physiotherapist class.

Here is the Patient Class. We assign a patient number randomly and that will be used to verify if the instance of the patient class is same or different.

package springbeansamples;

/**
 * @author nilendu.bhattacharya
 *
 */

public class Patient {
 String patientNumber=Integer.toString((int) (Math.random()*100000));
 /**
  * @return Returns the type.
  */

 public String getPatientNumber() {
  return patientNumber;
 }
 
}

 

Here is the Physiotherapist Class.

 

package springbeansamples;

/**
 * @author nilendu.bhattacharya
 */

public class Physiotherapist {
 Patient patient;
 /**
  * @return Returns the patient.
  */

 public Patient getPatient() {
  return patient;
 }
 /**
  * @param patient The patient to set.
  */

 public void setPatient(Patient patient) {
  this.patient = patient;
 }
 
 public void showPatientDetails(){
  Patient patient = enrolPatient();
//   Show the patient number of (hopefully brand new) new Patient instance
  System.out.println("New Patient Number is : "+patient.getPatientNumber());
 }
 
 public Patient enrolPatient(){
  return getPatient();
 }
}


This is the entry in the configuration file for the beans.


This the result. Notice that same patient instance is there the Physiotherapist instance.

May 21, 2010 3:50:56 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringTest.xml]
New Patient Number is : 34271
New Patient Number is : 34271

Here is the changed Physiotherapist class.

package springbeansamples;
 
/**
 * @author nilendu.bhattacharya
 */
public abstract class Physiotherapist {
 Patient patient;
 /**
  * @return Returns the patient.
  */
 public Patient getPatient() {
  return patient;
 }
 /**
  * @param patient The patient to set.
  */
 public void setPatient(Patient patient) {
  this.patient = patient;
 }
 
 public void showPatientDetails(){
  Patient patient = enrolPatient(); 
//   Show the patient number of (hopefully brand new) new Patient instance
  System.out.println("New Patient Number is : "+patient.getPatientNumber());
 }
 
 //This is where the lookup injection will take place.  This is abstract method. 
 public abstract Patient enrolPatient();
}

Bean configuration in the Spring configuration file for method lookup injection. Notice that in the bean physiotherapist we have reference to lookup-method

Here is the output which show how New instance of Patient is generated.

May 21, 2010 3:54:34 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringTest.xml]
New Patient Number is : 51362
New Patient Number is : 3906


Below is the MethodInjectionTest code. Use this class to test if new instance is created for the Patient class.

 

package springbeansamples;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
 
/**
 * @author nilendu.bhattacharya
 *
 */
public class MethodInjectionTest {
 public static void main(String[] args) {
 XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("SpringTest.xml"));
 
 Physiotherapist physiotherapist = (Physiotherapist) beanFactory.getBean("physiotherapist");
 physiotherapist.showPatientDetails();
 physiotherapist = (Physiotherapist) beanFactory.getBean("physiotherapist");
 physiotherapist.showPatientDetails();
 
 }
}