Spring中Bean的作用域singleton和prototype

什麼是作用域

singleton:單例模式,IOC容器在初始化的時候就會創建bean對象,並且是唯一的一個對象,以後如果要從IOC容器中獲取對象,都會獲取到該對象,不會再新建對象。

prototype:多例模式,IOC容器在初始化的時候不會創建bean對象,而是在每次getBean()的時候創建對象,並且每getBean()一次就創建一個對象。

 

如何指定作用域:
1.在xml配置文件的bean標籤中指定

<bean id="address" class="com.lee.entity.Address" scope="prototype">
</bean>

2.在註解中指定

@Controller
@Scope("prototype")
public class StudentController {

}

補充:singleton延遲加載(懶加載)可以讓單例模式在創建IOC容器時不創建對象,延遲到getBean()的時候再創建對象。

實現方法,加@lazy註解

@Controller
@Scope("prototype")
@Lazy
public class StudentController {

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章