My new website on Artificial Intelligence and Machine Learning www.aimlfront.com

Injecting Spring Beans into Java Servlets

If you are working in a Java Web Application and you are using Spring IoC Container in your application, there is a chance that you might have to inject Spring Beans into a Java Servlet.
Comparing with general spring injection, with Servlet it will be differ. Because servlet will initialized when init method will be excuted. And spring context file will be loaded before all servlets initialization using web.xml. Even if initialize servlets with Spring configuration it will be overrided by init method of servlet.
Now will see process of Injecting Spring Beans into Java Servlets
Goal: What I am trying to achive here retrieving the values from pojo in servlet based on spring injection to display.

Address.java
package com.javavillage.beans;

import org.springframework.stereotype.Component;

@Component
public class Address {
	private String location="Mount Road";
	private String city="Chennai";
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
}

applicationContext.xml
In spring context file need to be observed below points.
   context:component-scan:  To enable annotations on specific package.
   context:annotation-config:  To enable annotations.
   context:spring-configured:  To enable Configurable annotation.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util
		http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	
	<context:component-scan base-package="com.javavillage.beans"></context:component-scan>
	<context:annotation-config/>
	<context:spring-configured/>
	<bean id="address" class="com.javavillage.beans.Address">
		<property name="location" value="Hinjewadi"></property>
		<property name="city" value="Pune"></property>
	</bean>
	
</beans>
TestServlet.java
In TestServlet file need to be observed below points.
   @Configurable:  Marks a class as being eligible for Spring-driven configuration..    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this):  To enable autowire support on current class; as servlet will
   be initialized in init method, added using SpringBeanAutowiringSupport.
package com.javavillage.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.javavillage.beans.Address;

/**
 * Servlet implementation class TestServlet
 */
@Configurable
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private Address address;

	@Override
	public void init(ServletConfig config) throws ServletException{
		super.init(config);
		SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
		
	}
    /**
     * Default constructor. 
     */
    public TestServlet() {
    	//
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, 
	 *				HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		       
        PrintWriter out=response.getWriter();
        out.println("<br>Name: "+address.getCity());
        out.println("<br>Designation: "+address.getLocation());
        out.close();		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
				throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}
web.xml
Configured TestServlet in web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

	<display-name>Archetype Created Web Application</display-name>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<servlet>
		<servlet-name>TestServlet</servlet-name>
		<servlet-class>com.javavillage.servlet.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>TestServlet</servlet-name>
		<url-pattern>/TestServlet</url-pattern>
	</servlet-mapping>

</web-app>

pom.xml:
(jar entries for the application)
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.5</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.5</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<artifactId>spring-web</artifactId>
			<groupId>org.springframework</groupId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<artifactId>spring-context</artifactId>
			<groupId>org.springframework</groupId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<artifactId>spring-core</artifactId>
			<groupId>org.springframework</groupId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<artifactId>spring-beans</artifactId>
			<groupId>org.springframework</groupId>
			<version>3.0.5.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.0.5.RELEASE</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.4</version>
		</dependency>
Application Project Structure

Spring IOC on servlet package structure

After execution see below window for servlet with spring injection

SErvlet execution using spring IOC

If you face any problem with server startup because of amy class missing even after adding all jars, check Deployment Assembly. If you are not able to see Deployement Assembly in eclipse, add all the jars as per below screen. Problem will get resolved.
Double click on Tomcat server in server tab--> open launch Configuration--> Go to Class path tab add all the jars.

SErvlet execution using spring IOC