终于搞懂Spring中Scope为Request和Session的Bean了
之前只是很模糊的知道其意思,在request scope中,每个request创建⼀个新的bean,在session scope中,同⼀session中的bean都是⼀样的
但是不知道怎么⽤代码去验证它
今天可到验证它的代码了
⾸先定义⼀个简单的类
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class HelloMessageGenerator {
private String message;
@Override
public String toString() {
return getClass().getSimpleName() + "@" + HexString(hashCode());
}
}
然后定义⼀个配置类
import t.annotation.Bean;
import t.annotation.Configuration;
import org.t.annotation.RequestScope;
import org.t.annotation.SessionScope;
@Configuration
public class ScopesConfig {
@Bean
@RequestScope
public HelloMessageGenerator requestScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@SessionScope
public HelloMessageGenerator sessionScopedBean() {
return new HelloMessageGenerator();
}
}
最后定义个控制类
llect.Maps;
import java.util.Map;
import javax.annotation.Resource;
spring framework和spring的关系slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/scopes")
@Slf4j
public class ScopesController {
@Resource(name = "requestScopedBean")
private HelloMessageGenerator requestScopedBean;
@Resource(name = "sessionScopedBean")
private HelloMessageGenerator sessionScopedBean;
@GetMapping("/request")
public Map<String, String> getRequestScopeMessage() {
Map<String, String> result = wLinkedHashMap();
result.put("message", Message());
result.put("requestScopedBean", String());
requestScopedBean.setMessage("Good morning!");
return result;
}
@GetMapping("/session")
public Map<String, String> getSessionScopeMessage() {
log.info("getSessionScopeMessage(), sessionScopedBean:{}", sessionScopedBean);
Map<String, String> result = wLinkedHashMap();
result.put("message", Message());
result.put("sessionScopedBean", String());
sessionScopedBean.setMessage("Good morning!");
return result;
}
}
结果说明:
1. 对于请求:/scopes/request(request scope 请求地址),⽹页上的结果是:
对于任何⼀次请求,message为null,且requestScopedBean都不⼀致,所以是每个request都会重新创建⼀个bean
第⼀次请求:
{
message: null,
requestScopedBean: "HelloMessageGenerator@3ef0cae5"
}
之后的请求:
{
message: null,
requestScopedBean: "HelloMessageGenerator@c84a4f4"
}
2. 对于请求:/scopes/session(session scope 请求地址),⽹页上的结果始终是:
第⼀次请求,message为null,之后的每次请求message被置为Good morning!,并且sessionScopedBean固定为⼀个值,所以同⼀session下都使⽤着同⼀个bean 当重新换⼀个浏览器请求时,⼜会重复以上的操作
第⼀次请求:
{
message: null,
sessionScopedBean: "HelloMessageGenerator@f9f38d5"
}
之后的请求:
{
message: "Good morning!",
sessionScopedBean: "HelloMessageGenerator@f9f38d5"
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论