赞
踩
Spring支持6个作用域:singleton、prototype、request、session、application、websocket
@Controller
public class TestController {
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("service1",act.getBean("testService"));
model.addAttribute("service2",act.getBean("testService"));
model.addAttribute("service3",act.getBean("testService"));
return "scope";
}
}
service
public class TestService {
}
配置
<bean id="testService" class="cn.smbms.service.TestService" scope="singleton"/>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>service1:${service1}</h1>
<h1>service2:${service2}</h1>
<h1>service3:${service3}</h1>
</body>
</html>
只要服务不重启,无论访问多次,每次都会从容器中获取三次testService
配置
<bean id="testService" class="cn.smbms.service.TestService" scope="prototype"/>
第一次访问
第二次访问
java.lang.IllegalStateException: No Scope registered for scope name 'request'
修改controller,从容器中获取两次bean
@RestController
public class TestController {
@Resource
private TestService testService1;
@Resource
private TestService testService2;
@RequestMapping("/test")
public String test(){
return testService1 + "----" + testService2;
}
}
修改service层,这次使用注解
@Service
@RequestScope
public class TestService {
}
第一次访问
第二次访问
@Service
@SessionScope
public class TestService {
}
同一个Session多次请求,不变
换一个session(浏览器)
@Service
@ApplicationScope
public class TestService {
}
不重启项目,多次访问
重启项目在访问
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。