1. 程式人生 > >終於搞懂Spring中Scope為Request和Session的Bean了

終於搞懂Spring中Scope為Request和Session的Bean了

之前只是很模糊的知道其意思,在request scope中,每個request建立一個新的bean,在session scope中,同一session中的bean都是一樣的 但是不知道怎麼用程式碼去驗證它 今天可找到驗證它的程式碼了 首先定義一個簡單的類 ```java import lombok.Getter; import lombok.Setter; @Getter @Setter public class HelloMessageGenerator { private String message; @Override public String toString() { return getClass().getSimpleName() + "@" + Integer.toHexString(hashCode()); } } ``` 然後定義一個配置類 ```java 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(); } } ``` 最後定義個控制類 ```java 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") pu