Spring 的 Bean 的6种scope

Spring 的 Bean 的6种scope

singleton (default)prototype

以下只能用在web server,baeldung文件说实际上很少用

requestsessionapplicationwebsocket

singleton

预设是这种,每次从bean取的都是同一个instance

@Bean@Scope("singleton")public Person personSingleton() {    return new Person();}

prototype

每次从bean取出的instance,每次都会不一样,每次都会重新产生一个新的instance。

@Bean@Scope("prototype")public Person personPrototype() {    return new Person();}

request

每次的request,都会产生一个新的instance,但是在同一个request中,每次从bean取出的instance,都是同一个。

@Bean@RequestScopepublic Person personRequest() {    return new Person();}

session

每个session中,每次从bean取出的instance,都是同一个。

@Bean@SessionScopepublic Person personSession() {    return new Person();}

application

跟singleton是一样的,但範围更广,这个instance可以被用在同一个servelet context的多的servlet base中

@Bean@ApplicationScopepublic Person personApplication() {    return new Person();}

websocket

当websocket第一次连线时建立,跟singleton是一样的,但只存在这个websocket session内

@Bean@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)public Person personWebsocket() {    return new Person();}

@Bean是用在method的annotation,将method回传的instance存成一个Bean


reference
https://www.baeldung.com/spring-bean-scopes


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章