Bean 的作用域

2021-02-20

Spring bean 的作用域包含

  • singleton
  • prototype

web 应用中再加上

  • request
  • session
  • application
  • websocket

基于上一篇的应用进行改造,加入 bean,设置作用域。

spring xml 加入 prototype 的 User

<bean id="user2" class="constxiong.User" scope="prototype"/>

在 Controller 中加入各种作用域 bean 的请求

package constxiong.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;

import constxiong.User;

/**
 * controller
 * 
 * @author ConstXiong
 */
@Controller
public class IndexController {
	
	@Autowired
	private ApplicationContext context;
	
	@RequestMapping("singleton")
	@ResponseBody
	public String singlton() {
		User user1 = context.getBean("user1", User.class);
		return user1.toString();
	}
	
	@RequestMapping("prototype")
	@ResponseBody
	public String prototype() {
		User user2 = context.getBean("user2", User.class);
		return user2.toString();
	}
	
	@RequestMapping("request")
	@ResponseBody
	public String request() {
		User user3 = context.getBean("user3", User.class);
		return user3.toString();
	}
	
	@RequestMapping("session")
	@ResponseBody
	public String session() {
		User user4 = context.getBean("user4", User.class);
		return user4.toString();
	}
	
	@RequestMapping("application")
	@ResponseBody
	public String application() {
		User user5 = context.getBean("user5", User.class);
		return user5.toString();
	}
	
	@Bean
	@Scope(WebApplicationContext.SCOPE_REQUEST)
	private static User user3() {
		return new User();
	}
	
	@Bean
	@Scope(WebApplicationContext.SCOPE_SESSION)
	private static User user4() {
		return new User();
	}
	
	@Bean
	@Scope(WebApplicationContext.SCOPE_APPLICATION)
	private static User user5() {
		return new User();
	}
}

 

通过请求

  • http://localhost:8080/singleton,每次请求 User 都是同一个对象
  • http://localhost:8080/prototype,每次请求 User 都是不同的对象
  • http://localhost:8080/request,每次请求 User 都是不同的对象
  • http://localhost:8080/session,每一次会话周期内的请求 User 都是相同的对象,不同会话内间的 User 对象不同
  • http://localhost:8080/application,每个 ServletContext 内,返回同一个对象

ConstXiong 备案号:苏ICP备16009629号-3