Knowledge Walls
J2EE Technologies Tutorial
Hyderabad, Andhra Pradesh, India
How to use XmlWebApplicationContext in Spring Framework with Example
XmlWebApplicationContext used to reads beans.xml spring application context configuration from web location.
  • setConfigLocation method used to set path of the bean configuration file.
  • setServletContext method used to set servletcontext instance.
  • refresh method used to refresh the bean memory based on new config file.
Step.1 Start a Web based Spring application 
  1. Select New menu -> Dynamic Web Project
  2. Enter Project Name as "XmlWebApplicationContextWebExample"
  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.springexamples;

public class SayHello {
    public void sayGoodMorning(){
        System.out.println("Hi, Good Morning!");
    public void sayGoodEvening(){
        System.out.println("Hi, Good Evening!");
    public void sayGoodNight(){
        System.out.println("Hi, Good Night!");
package com.springexamples;


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


public class MyBeanReader extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        XmlWebApplicationContext context = new XmlWebApplicationContext();
        SayHello hello = (SayHello) context.getBean("hello");

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="hello" class="com.springexamples.SayHello" />
Output on Console 
Run /MyBeanReader servlet

On web
empty page

On Console
Hi, Good Morning!
Hi, Good Evening!
Hi, Good Night!
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