一 . 概述
在 spring 之中常用的 Bean 的生命周期常见的有单例模型和多例模型.
我们可以使用 @Scope 完成声明.
二 .@Scope
[1] 创建组件
- public class Car {
- }
- public class Bike {
- }
[2] 创建配置类
- @Configuration
- public class ScopeConfig {
- @Bean
- public Car car() {
- return new Car();
- }
- @Bean
- @Scope("prototype")
- public Bike bike() {
- return new Bike();
- }
- }
[3] 测试类
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(classes = ScopeConfig.class)
- public class ScopeTest {
- @Autowired
- private ApplicationContext context;
- @Test
- public void test1() {
- System.out.println(context.getBean("car") == context.getBean("car"));
- System.out.println(context.getBean("bike") == context.getBean("bike"));
- }
查看运行结果:
true false
我们通过结果就知道 Bean 的 Scope 了.
来源: http://www.bubuko.com/infodetail-2619085.html