Spring Boot Scope範圍學習
Scope的理解
顧明思意,Scope就是範圍的意思,工程分爲普通項目與web項目,所以範圍就分成了兩大類。
1、Singleton:一個Spring容器只有一個Bean實例。
2、Prototype:每次調用都會新建一個Bean案列。
3、Request:web項目中,會給每一個http request新建一個Bean實例。
4、Session:web項目中,會給每一個http session新建一個Bean案列。
SingletonService
package com.springboot.scope;
import org.springframework.stereotype.Service;
@Service
//默認狀態下是Singleton
public class SingletonService
{
}
ProptotypeService
package com.springboot.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
//註釋爲Proptotype
public class ProptotypeService {
}
ScopeConfig 配置類的編寫
package com.springboot.scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.springboot.scope")
//配置類掃描指定路徑
public class ScopeConfig {
}
Main的編寫
package com.springboot.scope;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main
{
public static void main(String ager[])
{
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(ScopeConfig.class);
ProptotypeService p1=context.getBean(ProptotypeService.class);
ProptotypeService p2=context.getBean(ProptotypeService.class);
SingletonService s1=context.getBean(SingletonService.class);
SingletonService s2=context.getBean(SingletonService.class);
if(p1.equals(p2))
{
System.out.println("p1==p2");
}
if(s1.equals(s2))
{
System.out.println("s1==s2");
}
context.close();
}
}
運行結果
這裏顯示s1=s2表明單項模式中只可以存在一個實例,故p1!=p2。