在看單例模式的時候,不經(jīng)意看到prototype和single在springmvc中的使用,記錄一下。
springMVC Controller默認(rèn)是單例的:
單例的原因有二:
1、為了性能市殷。
2、不需要多例束倍。
我這里說不需要的原因是看開發(fā)者怎么用了被丧,如果你給controller中定義很多的屬性,那么單例肯定會出現(xiàn)競爭訪問了绪妹。?
因此甥桂,只要controller中不定義屬性,那么單例完全是安全的邮旷。下面給個例子說明下:
@RestController
@RequestMapping("/api/")
@Scope("prototype")
@Slf4j
public class TestController {
private static int sts = 0;
private int index = 0;
@RequestMapping("/company")
public String getMessage(@RequestBody JSONObject jsonObject) {
System.out.println("==" + (sts++) + "," + (index++));
}
}
如果增加@Scope("prototype")黄选,輸出結(jié)果為:
==0,0
==1,0
==2,0
如果將@Scope("prototype")去掉/或者@Scope("singleton"),默認(rèn)使用單例模式婶肩,輸出結(jié)果為:
==0,0
==1,1
==2,2
從此可見办陷,單例是不安全的,會導(dǎo)致定義成員變量index數(shù)據(jù)錯誤律歼。
最佳實踐:
1民镜、不要在controller中定義成員變量。
2险毁、萬一必須要定義一個非靜態(tài)成員變量時候制圈,則通過注解@Scope("prototype"),將其設(shè)置為多例模式畔况。
只要不定義一個成員變量就行了鲸鹦。就可以不用@Scope("prototype")