{"id":3938,"date":"2020-07-06T15:41:58","date_gmt":"2020-07-06T10:11:58","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=3938"},"modified":"2020-07-06T15:42:00","modified_gmt":"2020-07-06T10:12:00","slug":"what-is-the-scope-of-a-bean","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/what-is-the-scope-of-a-bean\/","title":{"rendered":"What is the scope of a bean?"},"content":{"rendered":"\n<p>Bean scope decides which type of bean instance should be returned to the caller from the Spring container. Scopes are defined using @Scope annotation.<\/p>\n\n\n\n<p>There are six types of bean scopes in the latest version of the <a href=\"https:\/\/www.h2kinfosys.com\/blog\/what-is-the-spring-framework-in-java\/\">Spring framework<\/a>:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>singleton<\/li><li>prototype<\/li><li>request<\/li><li>session<\/li><li>application<\/li><li>WebSocket<\/li><\/ol>\n\n\n\n<p>The scopes request, session, application, and WebSocket are only available in a web-aware application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1] Singleton Scope: <\/strong><\/h3>\n\n\n\n<p>Singleton scope means that the container should create a single instance of a bean, and all the requests for that bean will return the same object. When there is no scope defined, the singleton scope is considered as default scope. When any modification is done to the object, it will reflect in all the references of that bean.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!-- A bean definition with singleton scope --&gt;\n&lt;bean id = \"...\" class = \"...\" scope = \"singleton\"&gt;\n&lt;\/bean&gt;<\/pre>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Step 1: First create an entity named as Person.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public class Person {\n&nbsp;&nbsp;&nbsp;&nbsp;private String name;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;\/\/ standard constructor, getters and setters\n}<\/pre>\n\n\n\n<p>Step 2: Define a bean with a singleton scope.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Bean\n@Scope(\"singleton\")\npublic Person personSingleton() {\n&nbsp;&nbsp;&nbsp;&nbsp;return new Person();\n}<\/pre>\n\n\n\n<p>Step 3: Create a Test.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">private static final String NAME = \"ABC\";&nbsp;\n@Test\npublic void givenSingletonScope_whenSetName_thenEqualNames() {\n&nbsp;&nbsp;&nbsp;&nbsp;ApplicationContext applicationContext =&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new ClassPathXmlApplicationContext(\"scopes.xml\");&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;Person personSingletonA = (Person) applicationContext.getBean(\"personSingleton\");\n&nbsp;&nbsp;&nbsp;&nbsp;Person personSingletonB = (Person) applicationContext.getBean(\"personSingleton\");&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;personSingletonA.setName(NAME);\n&nbsp;&nbsp;&nbsp;&nbsp;Assert.assertEquals(NAME, personSingletonB.getName());&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;((AbstractApplicationContext) applicationContext).close();\n}<\/pre>\n\n\n\n<p>Step 4: Scope.xml file<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;beans xmlns=\"https:\/\/www.springframework.org\/schema\/beans\"\n&nbsp;&nbsp;&nbsp;&nbsp;xmlns:xsi=\"https:\/\/www.w3.org\/2001\/XMLSchema-instance\"&gt;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean id=\"personSingleton\" class=\"org.spring.scopes.Person\" scope=\"singleton\"\/&gt;&nbsp;&nbsp;&nbsp;&nbsp;\n&lt;\/beans&gt;<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2] Prototype Scope: <\/strong><\/h3>\n\n\n\n<p>In prototype scope, a different instance is returned every time it is requested from the container.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!-- A bean definition with prototype scope --&gt;\n&lt;bean id = \"...\" class = \"...\" scope = \"prototype\"&gt;\n&lt;\/bean&gt;\n<\/pre>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Step 1: First create an entity named as Person.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public class Person {\n&nbsp;&nbsp;&nbsp;&nbsp;private String name;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;\/\/ standard constructor, getters and setters\n}\n<\/pre>\n\n\n\n<p>Step 2: Define a bean with prototype scope.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Bean\n@Scope(\"prototype\")\npublic Person personPrototype() {\n&nbsp;&nbsp;&nbsp;&nbsp;return new Person();\n}\n<\/pre>\n\n\n\n<p>Step 3: Create a Test File.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">private static final String NAME = \"ABC\";\nprivate static final String NAME_OTHER = \"XYZ\";&nbsp;\n@Test\npublic void givenPrototypeScope_whenSetNames_thenDifferentNames() {\n&nbsp;&nbsp;&nbsp;&nbsp;ApplicationContext applicationContext =&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new ClassPathXmlApplicationContext(\"scopes.xml\");&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;Person personPrototypeA = (Person) applicationContext.getBean(\"personPrototype\");\n&nbsp;&nbsp;&nbsp;&nbsp;Person personPrototypeB = (Person) applicationContext.getBean(\"personPrototype\");&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;personPrototypeA.setName(NAME);\n&nbsp;&nbsp;&nbsp;&nbsp;personPrototypeB.setName(NAME_OTHER);\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;Assert.assertEquals(NAME, personPrototypeA.getName());\n&nbsp;&nbsp;&nbsp;&nbsp;Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;((AbstractApplicationContext) applicationContext).close();\n}\n<\/pre>\n\n\n\n<p>Step 4: Scope.xml File<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;beans xmlns=\"https:\/\/www.springframework.org\/schema\/beans\"\n&nbsp;&nbsp;&nbsp;&nbsp;xmlns:xsi=\"https:\/\/www.w3.org\/2001\/XMLSchema-instance\"&gt;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean id=\"personSingleton\" class=\"org.spring.scopes.Person\" scope=\"prototype\"\/&gt;&nbsp;&nbsp;&nbsp;&nbsp;\n&lt;\/beans&gt;\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3] Request Scope: <\/strong><\/h3>\n\n\n\n<p>In the request scope, the Spring container creates a new instance for each and every HTTP request. For example, if there are 20 requests then the container will create 20 new instances and the instances are destructed when the request is complete.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!-- A bean definition with request scope --&gt;\n&lt;bean id = \"...\" class = \"...\" scope = \"request\"&gt;\n&lt;\/bean&gt;\n<\/pre>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Step 1: Request Scope can be defined as:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Bean\n@RequestScope\npublic HelloMessageGenerator requestScopedBean() {\n&nbsp;&nbsp;&nbsp;&nbsp;return new HelloMessageGenerator();\n}\n<\/pre>\n\n\n\n<p>Step 2: Define a Controller<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Controller\npublic class ScopesController {\n&nbsp;&nbsp;&nbsp;&nbsp;@Resource(name = \"requestScopedBean\")\n&nbsp;&nbsp;&nbsp;&nbsp;HelloMessageGenerator requestScopedBean;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;@RequestMapping(\"\/scopes\/request\")\n&nbsp;&nbsp;&nbsp;&nbsp;public String getRequestScopeMessage(final Model model) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;model.addAttribute(\"previousMessage\", requestScopedBean.getMessage());\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;requestScopedBean.setMessage(\"Good morning!\");\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;model.addAttribute(\"currentMessage\", requestScopedBean.getMessage());\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return \"scopesExample\";\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}\n<\/pre>\n\n\n\n<p>Step 3: Scope.xml File<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;beans xmlns=\"https:\/\/www.springframework.org\/schema\/beans\"\n&nbsp;&nbsp;&nbsp;&nbsp;xmlns:xsi=\"https:\/\/www.w3.org\/2001\/XMLSchema-instance\"&gt;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean id=\"personSingleton\" class=\"org.spring.scopes.Person\" scope=\"request\"\/&gt;&nbsp;&nbsp;&nbsp;&nbsp;\n&lt;\/beans&gt;\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>4] Session Scope: <\/strong><\/h3>\n\n\n\n<p>In session scope, the Spring container creates a new instance for each and every HTTP session. For example, if there are 20 sessions then container will create 20 new instances and the instances are destructed when the session ends.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!-- A bean definition with session scope --&gt;\n&lt;bean id = \"...\" class = \"...\" scope = \"session\"&gt;\n&lt;\/bean&gt;\n<\/pre>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Step 1: Session Scope can be defined as:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Bean\n@SessionScope\npublic HelloMessageGenerator sessionScopedBean() {\n&nbsp;&nbsp;&nbsp;&nbsp;return new HelloMessageGenerator();\n}\n<\/pre>\n\n\n\n<p>Step 2: Define a Controller<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Controller\npublic class ScopesController {\n&nbsp;&nbsp;&nbsp;&nbsp;@Resource(name = \"sessionScopedBean\")\n&nbsp;&nbsp;&nbsp;&nbsp;HelloMessageGenerator sessionScopedBean;\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;@RequestMapping(\"\/scopes\/session\")\n&nbsp;&nbsp;&nbsp;&nbsp;public String getSessionScopeMessage(final Model model) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;model.addAttribute(\"previousMessage\", sessionScopedBean.getMessage());\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sessionScopedBean.setMessage(\"Good afternoon!\");\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;model.addAttribute(\"currentMessage\", sessionScopedBean.getMessage());\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return \"scopesExample\";\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}\n<\/pre>\n\n\n\n<p>Step 3: Scope.xml File<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;beans xmlns=\"https:\/\/www.springframework.org\/schema\/beans\"\n&nbsp;&nbsp;&nbsp;&nbsp;xmlns:xsi=\"https:\/\/www.w3.org\/2001\/XMLSchema-instance\"&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean id=\"personSingleton\" class=\"org.spring.scopes.Person\" scope=\"session\"\/&gt;&nbsp;&nbsp;&nbsp;&nbsp;\n&lt;\/beans&gt;\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>5] Application Scope: <\/strong><\/h3>\n\n\n\n<p>In the application scope, the Spring container creates one instance per <a href=\"https:\/\/en.wikipedia.org\/wiki\/Runtime_system\" rel=\"nofollow noopener\" target=\"_blank\">web application runtime<\/a>. There can be multiple application scope instances for a single application.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!-- A bean definition with application scope --&gt;\n&lt;bean id = \"...\" class = \"...\" scope = \"application\"&gt;\n&lt;\/bean&gt;\n<\/pre>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<p>Step 1: Application Scope can be defined as:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Bean\n@ApplicationScope\npublic HelloMessageGenerator applicationScopedBean() {\n&nbsp;&nbsp;&nbsp;&nbsp;return new HelloMessageGenerator();\n}\n<\/pre>\n\n\n\n<p>Step 2: Define a Controller<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Controller\npublic class ScopesController {\n&nbsp;&nbsp;&nbsp;&nbsp;@Resource(name = \"applicationScopedBean\")\n&nbsp;&nbsp;&nbsp;&nbsp;HelloMessageGenerator applicationScopedBean;\n&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;@RequestMapping(\"\/scopes\/application\")\n&nbsp;&nbsp;&nbsp;&nbsp;public String getApplicationScopeMessage(final Model model) {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;model.addAttribute(\"previousMessage\", applicationScopedBean.getMessage());\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;applicationScopedBean.setMessage(\"Good afternoon!\");\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;model.addAttribute(\"currentMessage\", applicationScopedBean.getMessage());\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return \"scopesExample\";\n&nbsp;&nbsp;&nbsp;&nbsp;}\n}\n<\/pre>\n\n\n\n<p>Step 3: Scope.xml File<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;beans xmlns=\"https:\/\/www.springframework.org\/schema\/beans\"\n&nbsp;&nbsp;&nbsp;&nbsp;xmlns:xsi=\"https:\/\/www.w3.org\/2001\/XMLSchema-instance\"&gt;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean id=\"personSingleton\" class=\"org.spring.scopes.Person\" scope=\"application\"\/&gt;&nbsp;&nbsp;&nbsp;&nbsp;\n&lt;\/beans&gt;\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6] Websocket Scope: <\/strong><\/h3>\n\n\n\n<p>Websocket scope enables a two-way communication between the client and the host.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!-- A bean definition with WebSocket scope --&gt;\n&lt;bean id = \"...\" class = \"...\" scope = \"websocket\"&gt;\n&lt;\/bean&gt;\n<\/pre>\n\n\n\n<p>WebSocket Scope can be defined as:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@Bean\n@Scope(scopeName = \"websocket\", proxyMode = ScopedProxyMode.TARGET_CLASS)\npublic HelloMessageGenerator websocketScopedBean() {\n&nbsp;&nbsp;&nbsp;&nbsp;return new HelloMessageGenerator();\n}\n<\/pre>\n\n\n\n<p>Scope.xml File for Websocket scope looks like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;beans xmlns=\"https:\/\/www.springframework.org\/schema\/beans\"\n&nbsp;&nbsp;&nbsp;&nbsp;xmlns:xsi=\"https:\/\/www.w3.org\/2001\/XMLSchema-instance\"&gt;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean id=\"personSingleton\" class=\"org.spring.scopes.Person\" scope=\"websocket\"\/&gt;&nbsp;&nbsp;&nbsp;&nbsp;\n&lt;\/beans&gt;\n<\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Bean scope decides which type of bean instance should be returned to the caller from the Spring container. Scopes are defined using @Scope annotation. There are six types of bean scopes in the latest version of the Spring framework: singleton prototype request session application WebSocket The scopes request, session, application, and WebSocket are only available [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3948,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[636,1066,1067,1062,1068,1065,1063,1069],"class_list":["post-3938","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorials","tag-application","tag-prototype","tag-request","tag-scope-of-a-bean","tag-session","tag-singleton","tag-spring-framework","tag-websocket"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3938","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=3938"}],"version-history":[{"count":0,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/3938\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/3948"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=3938"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=3938"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=3938"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}