27 April 2019
Spring(4)----Bean Scope----part2
by Jerry Zhang
#Tip of the Day: I changed the memory of the virtual machine from 8G to 4G, but the speed is improved a little.
Web scopes
Web Context creation
To test the web scopes, we need to create a Web context for our application.
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">
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SpringServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Three bean classes. I only show RequestController.java here, the other two are similar.
@Controller
public class RequestController {
@RequestMapping("testRequest")
@ResponseBody
public String test(){
return this.toString();
}
}
spring.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.xsd">
<bean class="springioc.class008.ApplicationController"/>
<bean class="springioc.class008.RequestController"/>
<bean class="springioc.class008.SessionController"/>
</beans>
Run with Tomcat
To run our application, we need to create a tomcat server. Download a tomcat if you don’t have one.
Notice that I changed the Application context to : “/”
Then run this tomcat server, and open browser, go to “http://localhost:8080/testRequest”
then, we can get a response.springioc.class008.RequestController@2ce58ae3
Request scope
Every time we send a request, a new bean will be created. If we change the spring.xml file
<bean class="springioc.class008.ApplicationController" scope="request"/>
Then every time we refresh, we will get a new bean.
Session scope
Similarly, in each session, we have a same bean.
Application scope
In the whole application, we only have one single bean.
tags: Spring - framework, - Bean - Scope, - Java