Scope描述的是Spring容器是如何新建Bean的實例的。spring
Spring經常使用的Scope有如下幾種,經過@Scope註解來實現:session
爲了更好的理解,咱們經過具體的代碼示例來理解下Singleton與ProtoType的區別。測試
package scope; import org.springframework.stereotype.Service; @Service public class DemoSingletonService { }
由於Spring默認配置的Scope是Singleton,所以以上代碼等價於如下代碼:prototype
package scope; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; @Service @Scope("singleton") public class DemoSingletonService { }
package scope; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; @Service @Scope("prototype") public class DemoPrototypeService { }
package scope; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("scope") public class ScopeConfig { }
新建一個Main類,在main()方法中,分別從Spring容器中獲取2次Bean,而後判斷Bean的實例是否相等:3d
package scope; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class); DemoSingletonService s1 = context.getBean(DemoSingletonService.class); DemoSingletonService s2 = context.getBean(DemoSingletonService.class); DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class); DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class); System.out.println("s1 與 s2 是否相等:" + s1.equals(s2)); System.out.println("p1 與 p2 是否相等:" + p1.equals(p2)); context.close(); } }
運行結果以下:code
從運行結果也能夠看出,默認狀況下即Singleton類型的Bean,無論調用多少次,只會建立一個實例。
Singleton類型的Bean,@Scope註解的值必須是:singleton。
ProtoType類型的Bean,@Scope註解的值必須是:prototype。
即便是大小寫不一致也不行,如咱們將DemoPrototypeService類的代碼修改成:
package scope; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; @Service @Scope("PROTOTYPE") public class DemoPrototypeService { }
此時運行代碼,就會報錯:
源碼地址:https://github.com/zwwhnly/spring-action.git,歡迎下載。
《Java EE開發的顛覆者:Spring Boot實戰》
歡迎掃描下方二維碼關注公衆號:申城異鄉人。