Spring的常用配置之Bean的Scope

Bean的Scope
Scope描述的是Spring 容器如何创建Bean的示例。
通过@Scope注解来实现
Singleton:Spring容器只有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例
Prototype:每次调用新建一个Bean的实例
Request:web项目中给每个http request新建一个Bean实例
Session:web项目中,给每个http session新建一个Bean实例
GlobalSession:只在portal应用中有用,给每一个global http session新建一个Bean实例

另外,在Spring Batch中还有一个Scope是使用@StepScope

编写代码的过程中发现
只有@Service创建bean  实例相同
如果在下面继续注解@Scope("prototype")
就会发现两个实例并不是相等的。
他们的内存空间不同
@Service
@Scope("prototype")
public class DemoPrototypeService {

}

@Service
public class DemoSingletonService {


}
@Configuration
@ComponentScan("com.example.demo.scope")
public class ScopeConfig {

}

@SpringBootApplication
public class DemoApplication {

    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.err.println("s1 与 s2是否相等"+s1.equals(s2));
        System.err.println("p1 与 p2是否相等"+p1.equals(p2));

        context.close();
    }

}

结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值