2.1.1 点睛
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)Global Session:这个只在portal 应用中有用,给每一个global http session 新建一个Bean实例。
另外,在Spring Batch 中还有一个Scope 是使用@StepScope,我们将在批处理一节介绍这个Scope 。
本例简单演示默认的singleton和Prototype,分别从Spring 容器中获得2 次Bean,判断Bean 的实例是否相等。
2.1.2 示例
(1)编写Singleton的Bean
package com.discry.springboot_in_action.ch2;
import org.springframework.stereotype.Service;
@Service
public class DemoSingletonService {
}
代码解释
①默认为Singleton,相当于@Scope(“singleton”)
(2)编写Prototype的Bean
package com.discry.springboot_in_action.ch2;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
public class DemoPrototypeService {
}
(3)配置类
代码解释
①声明Scope 为Prototype
package com.discry.springboot_in_action.ch2.configs;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.discry.springboot_in_action")
public class ScopeConfig {
}
(4)运行
package com.discry.springboot_in_action.ch2;
import com.discry.springboot_in_action.ch2.configs.ScopeConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootScopeTest {
@Test
public void scopeTest() {
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));
}
}
结果: