
一. 点睛
Scope描述的是Spring容器如何新建Bean的实例的。Spring的Scope有以下几种,通过@Scope注解来实现。
(1)
Singleton:一个Spring容器中只有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例。
(2)Prototype:每次调用新建一个Bean的实例。
(3)Request:Web项目中,给每一个http request新建一个bean实例。
(4)Session:Web项目中,给每一个http session新建一个bean实例。
(5)GlobalSession:这个只在portal应用中有用,给每一个global http session新建一个bean实例。
另外,在SpringBatch中还有一个Scope是使用@StepScope,后面有时间写会说到。
下面简单演示默认的singleton和prototype,分别从Spring容器中获得2次Bean,判断Bean的实例是否相等。
二. 实例
1. 编写Singleton的Bean
package org.light4j.sping4.usually.scope;
import org.springframework.stereotype.Service;
@Service //①
public class DemoSingletonService {
}
代码解释:
①默认为
Singleton,相当于@Scope("singleton")。
2. 编写Prototype的Bean
package org.light4j.sping4.usually.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")//①
public class DemoPrototypeService {
}
代码解释:
①声明
Scope为Prototype
3. 配置类
package org.light4j.sping4.usually.scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("org.light4j.sping4.usually.scope")
public class ScopeConfig {
}
4. 运行
package org.light4j.sping4.usually.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();
}
}
运行结果如下图所示:

(8). 源代码示例:
打赏 欢迎关注人生设计师的微信公众账号
公众号ID:longjiazuoA
