XmlWebApplicationContext
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
-
Select New menu -> Dynamic Web Project
-
Enter Project Name as "XmlWebApplicationContextWebExample"
-
Click Next, Selecting Target runtime as Apache Tomcat 7.0
-
Click Next, Check Generate web.xml deployment descriptor then click on "Finish"
-
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 java.io.IOException;
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.web.context.support.XmlWebApplicationContext;
@WebServlet("/MyBeanReader")
public class MyBeanReader extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setConfigLocation("/WEB-INF/beans.xml");
context.setServletContext(request.getServletContext());
context.refresh();
SayHello hello = (SayHello) context.getBean("hello");
hello.sayGoodMorning();
hello.sayGoodEvening();
hello.sayGoodNight();
}
}
|
<?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="hello" class="com.springexamples.SayHello" />
</beans>
|
Output on Console
Run /MyBeanReader servlet
On web
empty page
On Console
Hi, Good Morning!
Hi, Good Evening!
Hi, Good Night!
|