博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Spring 4.x】Spring常用配置_Bean的Scope
阅读量:3944 次
发布时间:2019-05-24

本文共 2040 字,大约阅读时间需要 6 分钟。

概念

Scope描述的是Spring容器如何新建Bean的实例的

Spring的Scope有以下几种,通过@Scope注解来实现。

(1)Singleton:单例模式,一个Spring容器中只有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例。eg:数据库链接。

(2)Prototype:原型模式,每次调用新建一个Bean的实例。
(3)Request:Web项目中,给每一个http request新建一个Bean实例。eg:搜索引擎中的一次查询。
(4)Session:Web项目中,给每一个http session新建一个Bean实例。
(5)GlobalSession:这个只在portal应用中有用,给每一个global http session新建一个Bean实例。

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

示例

演示默认的singleton和Prototype,分别从Spring容器中获得2次Bean,判断Bean的实例是否相等。

(1)编写Singleton的Bean。

package com.wisely.highlight_spring4.ch2.scope; import org.springframework.stereotype.Service; @Service //1 默认为Singleton,相当于@Scope(“singleton”)public class DemoSingletonService {
}①默认为Singleton,相当于@Scope(“singleton”)

(2)编写Prototype的Bean。

package com.wisely.highlight_spring4.ch2.scope;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Service;@Service@Scope("prototype") //1 声明Scope为Prototypepublic class DemoPrototypeService {
}①声明Scope为Prototype

(3)配置类。

package com.wisely.highlight_spring4.ch2.scope;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScan("com.wisely.highlight_spring4.ch2.scope")public class ScopeConfig {
}

(4)运行。

package com.wisely.highlight_spring4.ch2.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)); //true System.out.println("p1与p2是否相等:"+p1.equals(p2)); //false context.close(); }}

转载地址:http://ghjwi.baihongyu.com/

你可能感兴趣的文章
BFD
查看>>
docker网络
查看>>
锐捷交换机的多对多镜像口
查看>>
Linux系统修改编码
查看>>
word文档不能显示图片的处理
查看>>
linux的多桌面环境Xephyr
查看>>
初探debian桌面的管理启动
查看>>
七层协议图
查看>>
华为交换机作为AC的条件
查看>>
禁用Ubuntu 15.04登录界面显示客人会话(简单-实用)
查看>>
linux X下安装的软件
查看>>
Linux监测某一时刻对外的IP连接情况
查看>>
CentOS7 最小环境安装Jumpserver 1.0版脚本
查看>>
X-Security X的安全控制
查看>>
openVAS的安装
查看>>
Centos 6.5 初始安装无网卡驱动解决方法
查看>>
linux中的网桥bridge
查看>>
linux中的teaming与bonding
查看>>
LVM
查看>>
用shell切分文件--split
查看>>