在默認狀況下,Spring應用上下文中全部的bean都是以單例(singleton)的形式建立的,即無論給定的一個bean被注入到其餘bean多少次,每次所注入的都是同一個實例。java
Spring定義了多種做用域,能夠基於這些做用域建立bean:git
單例是默認的做用域,若是要使用其它的做用域建立bean,須要使用@Scope
註解,該註解能夠和@Component
,@Service
,@Bean
等註解一塊兒使用。github
爲了更好的理解,咱們經過具體的代碼示例來理解下Singleton與ProtoType的區別。spring
package chapter03.scope;
import org.springframework.stereotype.Service;
@Service
public class DemoSingletonService {
}
複製代碼
由於Spring默認配置的Scope是Singleton,所以以上代碼等價於如下代碼:微信
package chapter03.scope;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class DemoSingletonService {
}
複製代碼
上面的代碼也能夠寫成@Scope("singleton")
。測試
若是是自動裝配bean,語法爲:spa
package chapter03.scope;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DemoPrototypeService {
}
複製代碼
上面的代碼也能夠寫成@Scope("prototype")
。prototype
若是是在Java配置類中聲明bean,語法爲:code
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public DemoPrototypeService demoPrototypeService() {
return new DemoPrototypeService();
}
複製代碼
若是是在xml中聲明bean,語法爲:cdn
<bean id="demoPrototypeService" class="chapter03.scope.DemoPrototypeService" scope="prototype"/>
複製代碼
package chapter03.scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("chapter03.scope")
public class ScopeConfig {
}
複製代碼
新建一個Main類,在main()方法中,分別從Spring容器中獲取2次Bean,而後判斷Bean的實例是否相等:
package chapter03.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();
}
}
複製代碼
運行結果以下:
從運行結果也能夠看出,默認狀況下即Singleton類型的Bean,無論調用多少次,只會建立一個實例。
Singleton類型的Bean,@Scope註解的值必須是:singleton。
ProtoType類型的Bean,@Scope註解的值必須是:prototype。
即便是大小寫不一致也不行,如咱們將DemoPrototypeService類的代碼修改成:
package chapter03.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("PROTOTYPE")
public class DemoPrototypeService {
}
複製代碼
此時運行代碼,就會報錯:
源碼地址:github.com/zwwhnly/spr…,歡迎下載。
汪雲飛《Java EE開發的顛覆者:Spring Boot實戰》
最後,歡迎關注個人微信公衆號:「申城異鄉人」,全部博客會同步更新。