Web/Spring

Spring bean scope

mayleaf 2023. 1. 28. 23:58

Today I have learned about Spring bean scope.

The most generally used scopes are Singleton, request, prototype, and etc..

Singleton

singleton scope is DEFAULT for spring bean. Most of beans we used are singleton. Picture your API server code.

@Controller, @Service, @Repository, @Component, these are singleton. As at last I have written, singleton beans are 

created, registered, and injected their dependencies at the time of spring container initialization.

 

Prototype

Prototype bean is instantiated when it called. After it created and registered, and injected, spring call the initialization callback of it. However, spring doesn't care about the end of prototype bean. Therefore, @PreDestroy or @Bean(destroyMethod="thatMethod") would never work(Without involving of BeanPostProcessor). It removed when all references to that instance are removed.

Request

Request scope included in Spring MVC.

A request-scoped bean is created for each HTTP request connection, also destroyed the connection closed.

On my opinion, It would used for form, request logger, etc..