首页 > 代码库 > Spring学习四----------Bean的配置之Bean的配置项及作用域

Spring学习四----------Bean的配置之Bean的配置项及作用域

Bean的作用域(每个作用域都是在同一个Bean容器中)

1.singleton:单例,指一个Bean容器中只存在一份(默认)

2.prototype:每次请求(每次使用)创建新的实例,destory方式不生效

3.request:每次http请求创建一个实例且仅在当前request内生效(只能在web中使用

4.session:同上,每次http请求创建一个实例,当前session内有效(只能在web中使用

5.global session:基于portlet的web中有效(portlet定义了global session),如果是在单个web中,同session。(只能在web中使用

实例

1.singleton和prototype

  1.1 目录结构

技术分享

  1.2 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.spring</groupId>
	<artifactId>Spring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Spring</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.3.7.RELEASE</spring.version>
	</properties>

	<dependencies>
		<!-- junit依赖 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<!-- spring依赖 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-core</artifactId>
		    <version>${spring.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-beans</artifactId>
		    <version>${spring.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context</artifactId>
		    <version>${spring.version}</version>
		</dependency>
	</dependencies>
</project>

  1.3 spring-beanscope.xml(scope="singleton" || scope="prototype")

<?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 id="beanScope" class="org.spring.bean.BeanScope" scope="singleton"/>        
        
</beans>

  1.4 BeanScope.java

package org.spring.bean;

public class BeanScope {

	public void say () {
		
		System.out.println("hashCode:" + this.hashCode());//通过hashCode判断是否是同一个实例
		
	}

}

  1.5 UnitTestBase.java

package org.spring.ioc.test;

import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

/**
 * 单元测试初始化类
 *
 */
public class UnitTestBase {
	
	private ClassPathXmlApplicationContext context;
	private String springXmlPath;
	
	/**
	 * 无参构造器
	 */
	public UnitTestBase() {
		
	}

	/**
	 * 含参构造器
	 * 
	 * @param springXmlPath
	 * 						spring配置文件路径
	 */
	public UnitTestBase(String springXmlPath) {
		
		this.springXmlPath = springXmlPath;
		
	}
	
	/**
	 * 初始化spring配置文件
	 */
	@Before//在@Test注解的方法执行前执行
	public void before() {
		
		if(StringUtils.isEmpty(springXmlPath)) {//默认spring配置文件路径
			springXmlPath = "classpath*:spring-*.xml";
		}
		//加载配置文件,一个context表示一个容器
		context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]+"));
		//启动组件
		context.start();
		
	}
	
	/**
	 * 销毁spring组件
	 */
	@After//在@Test注解的方法执行后执行
	public void after() {
		
		context.destroy();//销毁组件
		
	}
	
	/**
	 * 获取spring中定义的bean实例
	 * 
	 * @param beanId
	 * 					
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected <T extends Object> T getBean(String beanId) {
		
		return (T) context.getBean(beanId);
		
	}
	
	/**
	 * 获取spring中定义的bean实例
	 * 
	 * @param clazz
	 * 				
	 * @return
	 */
	protected <T extends Object> T getBean(Class<T> clazz) {
		
		return (T) context.getBean(clazz);
		
	}

}

  1.6 TestBeanScope.java

package org.spring.ioc.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.spring.bean.BeanScope;

@RunWith(BlockJUnit4ClassRunner.class)//指定JUnit默认执行类
public class TestBeanScope extends UnitTestBase {
	
	public TestBeanScope() {//通过构造方法传入spring配置文件路径
		
		super("classpath*:spring-beanScope.xml");
		
	}
	
	@Test
	public void testScope() {
		
		BeanScope beanScope = super.getBean("beanScope");
		beanScope.say();
		
		/**
		 * 若在两个方法中执行这两行代码,则hashCode会不同。
		 * 因为每个test方法执行前都会执行@Before,会重新加载spring配置文件,此时是在两个容器中,所以不同
		 */
		BeanScope beanScope2 = super.getBean("beanScope");
		beanScope2.say();
		
	}
	
}

  1.7 singleton效果预览

技术分享

  1.8 prototype效果预览

技术分享

 2.request和session

  2.1 项目结构

技术分享

 

   2.2 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	
	<modelVersion>4.0.0</modelVersion>
	
	<groupId>org.spring</groupId>
	<artifactId>springBeanScope</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>springBeanScope Maven Webapp</name>
	<url>http://maven.apache.org</url>
	
	<properties>
		<spring.version>4.3.7.RELEASE</spring.version>
	</properties>
	
	<dependencies>
		<!-- junit依赖 -->
  		<dependency>
		    <groupId>junit</groupId>
		    <artifactId>junit</artifactId>
		    <version>4.12</version>
		    <scope>test</scope>
	  	</dependency>
	  	<!-- spring核心依赖 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-core</artifactId>
		    <version>${spring.version}</version>
		</dependency>
	  	<!-- spring web层依赖 -->
	  	<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-webmvc</artifactId>
		    <version>${spring.version}</version>
		</dependency>
		<!-- jstl -->
		<dependency>
		    <groupId>jstl</groupId>
		    <artifactId>jstl</artifactId>
		    <version>1.2</version>
		</dependency>
		<!-- servlet -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>3.1.0</version>
	</dependency>
		
	</dependencies>
  
  	<build>
    	<finalName>springBeanScope</finalName>
  	</build>
  	
</project>

  2.3 mvc-dispatcher-servlet.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"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
    <!-- 开启包扫描 -->
    <context:component-scan base-package="org.spring.*"/>
    
    <!-- 开启注解 -->
    <mvc:annotation-driven/>
    
    <!-- 定义视图解析器 -->
    <bean id="viewResolver" 
    	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<property name="prefix" value="http://www.mamicode.com/WEB-INF/jsp/"/>
    	<property name="suffix" value="http://www.mamicode.com/.jsp"/>	
   	</bean>
   	
</beans>

  2.4 BeanScope.xml

package org.spring.bean;

public class BeanScope {

	public int say () {
		
		return this.hashCode();//通过返回的hashCode判断是否是同一个实例
		
	}

}

  2.5 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 id="beanScope" class="org.spring.bean.BeanScope" scope="singleton"/>
        
</beans>

  2.6 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
  	version="3.0" metadata-complete="true">
  	
  	<!-- 启动spring的监听器,默认加载applicationContext.xml -->
  	<listener>
  		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  	</listener>
  	
  	<!-- 自定义spring配置文件路径 -->
  	<context-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:spring.xml</param-value>
  	</context-param>
  	
  	<!-- 拦截所有请求,交由springMVC处理 -->
  	<servlet>
  		<servlet-name>springMVC</servlet-name>
  		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  		<init-param>
  			<param-name>contextConfigLocation</param-name>
  			<param-value>classpath:mvc-dispatcher-servlet.xml</param-value>
  		</init-param>
  	</servlet>
  	<servlet-mapping>
  		<servlet-name>springMVC</servlet-name>
  		<url-pattern>/</url-pattern>
  	</servlet-mapping>
  	
</web-app>

  2.7 BeanScopeAction.java

package org.spring.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.spring.bean.BeanScope;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class BeanScopeAction implements ApplicationContextAware {

	private ApplicationContext context;
	
	@RequestMapping("/")
	public String testScope(ModelMap map, HttpSession session) {
		
		BeanScope scope = (BeanScope) context.getBean("beanScope");
		List<Integer> list = new ArrayList<Integer>();
		for(int i = 0; i < 3; i++){
			list.add(scope.say());
		}
		map.addAttribute("list", list);
		map.addAttribute("session", session);
		return "scope";
		
	}

	public void setApplicationContext(ApplicationContext context) throws BeansException {
		
		this.context = context;
		
	}
	
}

  2.8 scope.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring作用域测试</title>
</head>
<body>
	<font color="red">Session:${session }</font><br/>
	<c:forEach var="hashCode" items="${list }" varStatus="status">
		第${status.index + 1 }次获取实例:${hashCode }<br/>
	</c:forEach>
</body>
</html>

  2.9 效果预览

    需刷新才能看见效果,截图表达不清晰,可复制代码自行运行刷新查看结果。

3.global session

  需多个项目才能看见结果,此处不做测试。

参考:http://www.imooc.com/video/3750/

Spring学习四----------Bean的配置之Bean的配置项及作用域