之前只是很模糊的知道其意思:在request scope中,每個request創建一個新的bean;在session scope中,同一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() + "@" + Integer.toHexString(hashCode());
}
}
然後定義一個配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.context.annotation.SessionScope;
@Configuration
public class ScopesConfig {
@Bean
@RequestScope
public HelloMessageGenerator requestScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@SessionScope
public HelloMessageGenerator sessionScopedBean() {
return new HelloMessageGenerator();
}
}
最後定義個控制類
import com.google.common.collect.Maps;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.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 = Maps.newLinkedHashMap();
result.put("message", requestScopedBean.getMessage());
result.put("requestScopedBean", requestScopedBean.toString());
requestScopedBean.setMessage("Good morning!");
return result;
}
@GetMapping("/session")
public Map<String, String> getSessionScopeMessage() {
log.info("getSessionScopeMessage(), sessionScopedBean:{}", sessionScopedBean);
Map<String, String> result = Maps.newLinkedHashMap();
result.put("message", sessionScopedBean.getMessage());
result.put("sessionScopedBean", sessionScopedBean.toString());
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"
}
spring-bean-scopes - baeldung
spring 組件@Scope(request,session)示例 - cnblogs