Scope描述的是Spring容器是如何新建Bean的实例的。
Spring常用的Scope有以下几种,通过@Scope注解来实现:
为了更好的理解,我们通过具体的代码示例来理解下Singleton与ProtoType的区别。
package scope;
import org.springframework.stereotype.Service;
@Service
public class DemoSingletonService {
}
因为Spring默认配置的Scope是Singleton,因此以上代码等价于以下代码:
package scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("singleton")
public class DemoSingletonService {
}
package scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
public class DemoPrototypeService {
}
package scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("scope")
public class ScopeConfig {
}
新建一个Main类,在main()方法中,分别从Spring容器中获取2次Bean,然后判断Bean的实例是否相等:
package 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 scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("PROTOTYPE")
public class DemoPrototypeService {
}
此时运行代码,就会报错:
源码地址:https://github.com/zwwhnly/spring-action.git,欢迎下载。
《Java EE开发的颠覆者:Spring Boot实战》
欢迎扫描下方二维码关注公众号:申城异乡人。
Spring入门(五):Spring Bean Scope讲解
原文:https://www.cnblogs.com/zwwhnly/p/11066162.html