Spring 的 Bean 的6种scope
singleton (default)prototype以下只能用在web server,baeldung文件说实际上很少用
requestsessionapplicationwebsocketsingleton
预设是这种,每次从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