Creating an ApplicationContext in Spring from a web application

In web application ApplicationContext is created using Context Loaders. there are two implementations of context loader.

ContextLoaderListener : It is listener implementation that is added to web.xml file.
ContextLoaderServlet : It is servlet implementation that is configured with load-on-startup tag in web.xml.

ContextLoaderListener is simple way to use the spring in web application. this listener accept contextConfigLocation parameter from context-parama.
You have to enter following code in web.xml file

define contextConfigLocation parameter in context-param tag.

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/services.xml</param-value>
</context-param> 

services.xml is the Spring configuration file in which you define beans.

Add the ContextLoaderListener listener.

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Here is the complete source code for the example demonstrating this.

InputService.java

package com.techartifact.example.spring.service;
import java.util.Random;
import java.util.Scanner;
public class InputService {
    public int getIntValue() {
        Random r=new Random();
        int val=r.nextInt();
        System.out.println("Returning value = "+val);
        return val;
    }
}

OutputService.java

package com.techartifact.example.spring.service;
public class OutputService{
    public int write(int x) {
        System.out.println("Output is "+x);
        return x;
    }
}

CalServlet .java

package com.techartifact.example.spring.servlets;

import com.techartifact.example.spring.service.CalcMachine;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CalServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        CalcMachine cal = (CalcMachine) ac.getBean("cal");
        response.getWriter().print("Adding of numbers is = " + cal.doAdd());
        response.getWriter().close();
    }
}


services.xml

<?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="in" class="com.techartifact.example.spring.service.InputService"/>
    <bean id="out" class="com.techartifact.example.spring.service.OutputService"/>

    <bean id="cal" class="com.techartifact.example.spring.service.CalcMachine">
        <property name="inputService">
            <ref bean="in" />
        </property>
        <property name="outputService">
            <ref bean="out" />
        </property>
    </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>DI2_web</display-name>

    <servlet>
        <description></description>
        <display-name>CalServlet</display-name>
        <servlet-name>CalServlet</servlet-name>
        <servlet-class>com.techartifact.example.spring.servlets.CalServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CalServlet</servlet-name>
        <url-pattern>/CalServlet</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/services.xml</param-value>
    </context-param>

     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 
   
</web-app>

Run example

Download full example code from here spring-webapplication

Go to project directory [spring-webapplication] in command shell and run following command using maven

mvn clean package
mvn -Pcargo-run

You should see following output in your browser

http://localhost:8080/springapp/CalServlet

What is IoC or Spring IOC?

There is a lot of confusion about the definition of the IoC container – some equate it with a design pattern called Dependency Injection – but in reality IoC is much larger than dependency injection.

Inversion of Control (IoC) is an object-oriented programming practice where the object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis.

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

Steps to use the inversion of control (IOC) with spring framework.

=> Create one .xml file to configure the components and services.

=> We need to define classes and its properties.

=> Mention the service with its component as per springs framework
guidelines so that Spring container can create a object for us.

Explanation:

Class

package com.techartifact.vinay;

public class RefClass {

                private RefClass newRefClass;

                public RefClass getRefClass() {

                                return newRefClass;

                }

                public void setNewRefClass(RefClass newRefClass) {

                                this.newRefClass = newRefClass;

                }

}

Configuration file


 <bean id="createRefClass" class="com.techartifact.vinay.RefClass">

        <property name="newRefClass"/>

 </bean>


Here RefClass is a class which has getter and setter for newRefClass property.

Now spring container takes the responsibility to create the object of RefClass class with object name newRefClass which defined in the property tag with name attribute and set the value automatically when it is used.

How to configure Circular dependencies in Spring

Suppose you have a scenario like this :

you have a class A which requires an instance of class B and class B requires instance of class A . So this is called circular dependencies and you are configuring this using constructor injection like this :

Eg:

public class A {	
	private B b;	
	
	public A(B b){
        this.b=b;
       }		
}

public class B {
	
	private A a;
	private int age;
	
	public B(A a, int age){
        this.b=b;
        this.age=age;
       }
	public void show(){
		 System.out.println("vaue of age is "+age);
	}

}

And configuration will be like this :

When you will try to run this program, it will throw BeanCurrentlyInCreationException.

One possible solution to this issue is to edit the source code of some of your classes to be configured via setters instead of via constructors. Another solution is not to use constructor injection and stick to setter injection only.

Solution :

public class A {
	
	private B b;	
	
	

	public B getB() {
		return b;
	}

	public void setB(B b) {
		this.b = b;
	}
	
}

public class B {
	
	private A a;
	private int age;
	
		
	public A getA() {
		return a;
	}

	public void setA(A a) {
		this.a = a;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public void show(){
		 System.out.println("vaue of age is "+age);
	}

}

Configuration will be like this.

<?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-2.5.xsd">

       <bean id="a" class="study.spring.beans.A">
       <property name="b" ref="b"></property>        
       </bean>
       
       
       <bean id="b" class="study.spring.beans.B">
        <property name="a" ref="a"></property>
        <property name="age" value="24"></property>
       </bean>

</beans>

Enjoy Coding….

Thanks