Knowledge Walls
J2EE Technologies Tutorial
Hyderabad, Andhra Pradesh, India
How to access ApplicationContext (Bean-Factory) of Spring in Web Servlet with Example
Below is an example of "How to access ApplicationContext (Bean-Factory) of Spring in Web Servlet with Example".
Step.1 Start a Java Project with required jars 
  1. Select New menu -> Dynamic Web Project
  2. Enter Project Name as "ApplicationContextAccessInWebServletExample"
  3. Click Next, Selecting Target runtime as Apache Tomcat 7.0
  4. Click Next, Check Generate web.xml deployment descriptor then click on "Finish"
  5. Copy and paste Spring's 21 Framework Jars and commons-logging-1.1.jar into /WEB-INF/lib
Step.2 Project Explorer Preview
package com.knowledgewalls;

import org.springframework.stereotype.Component;

public class RndHolder {
    private int rndNumber;
    public int getRndNumber(){
        return rndNumber;
    public void setRndNumber(int rndNumber){
        this.rndNumber = rndNumber;
    public void generateRndNumber(){
        this.rndNumber = (int) (Math.random() * 99999);
package com.knowledgewalls;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;

public class ShowAccountDetails extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(req.getServletContext());
            RndHolder rndHolder = (RndHolder) context.getBean("rndHolder");
        resp.getWriter().write("Rnd Number: "+rndHolder.getRndNumber());
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:component-scan base-package="com.knowledgewalls" />
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">
    <param-value>/WEB-INF/beans-servlet.xml </param-value>
Hints. Run (Run on Server)

Output: 01

Output: 02
Download as Zip 
Link to download

Click on File menu. then click "Download"
Best Lessons of "Spring 3.0 Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details