Analysis of scope request usage of spring actual bean

This article describes the scope request usage of spring actual bean. Share with you for your reference, as follows:

One configuration

1 applicationContext. xml

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/beans"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
  <!-- 指定使用request作用域 -->
  <bean id="p" class="org.crazyit.app.service.Person"
    scope="request"/>
</beans>

2 web. xml

<?xml version="1.0" encoding="GBK"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
  http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>
</web-app>

Second bean

package org.crazyit.app.service;
public class Person
{
  private int age;
}

Three views

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ page import="org.springframework.web.context.*" %>
<%@ page import="org.springframework.web.context.support.*" %>
<%@ page import="org.crazyit.app.service.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Spring Bean的作用域</title>
</head>
<body>
<%
// 获取Web应用初始化的spring容器
WebApplicationContext ctx =
  WebApplicationContextUtils.getWebApplicationContext(application);
// 两次获取容器中id为p的Bean
Person p1 = (Person)ctx.getBean("p");
Person p2 = (Person)ctx.getBean("p");
out.println((p1 == p2) + "<br/>");
out.println(p1);
%>
</body>
</html>

Four tests

Readers interested in more Java related content can view the topics on this site: introduction and advanced tutorial of spring framework, tutorial of Java data structure and algorithm, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills

I hope this article will be helpful to you in Java programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>