目錄
1. 說明
@Scope是指定IOC組件的作用域,是單例存在的還是多例的等等,對應的XML如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.yibai.spring.annotation.bean.Person" scope="prototype" />
</beans>
2. 註解說明
@Scope可選值有4個
singleton:Spring IOC容器中只會存在一個共享的bean實例,並且所有對bean的請求,只要id與該bean定義相匹配,則只會返回bean的同一實例;
prototype:每一次請求都會產生一個新的bean實例,相當與一個new的操作,對於prototype作用域的bean,Spring不會對一個prototype的bean的整個生命週期管理,IOC將裝配好的實例返回個客戶端之後,該bean的操作處理都由客戶端管理;
request:在Web應用中,request表示該針對每一次HTTP請求都會產生一個新的bean,同時該bean僅在當前HTTP request內有效;
session:在Web應用中,request表示該針對每一次HTTP請求都會產生一個新的bean,同時該bean僅在當前HTTP request內有效;
3. 註解用法
當被@Component, @Repository, @Service, @Controller或者已經聲明過@Component自定義註解標記時
@Configuration
public class MainConfigForScope {
@Bean
@Scope(value = "prototype")
public Address address() {
return new Address();
}
}
當使用@Bean標記,通過方法返回時
@Setter
@Getter
@ToString
@Component
@Scope(value = "singleton")
public class Address {
private String country;
private String province;
private String detail;
}
4. 組件依賴組件
當Person依賴Address:
當Address是prototype,Person是singleton時,每一次請求Address都是新組裝的bean,每一次請求Person的時候,Person是單例的,自然依賴的Address也是同一個;
當Address是singleton,Person是prototype時,Person是多例的,但是所有Person依賴的Address是同一個;