×
☰ See All Chapters

Spring @Scope Annotation

Singleton scope is the default scope in spring. To set the scope for the bean we can use @Scope annotation in conjunction with @Bean. @Scope indicates the name of a scope to use for the instance returned from the method. We can use @Scope annotation in conjunction with @Component, @Scope indicates the name of a scope to use for instances of the annotated type. By supplying value to value attribute of @scope annotation we can specify the desired scope. We can supply the desired scope as a String value, or the BeanDefinition interface provides string constants for singleton and prototype scope values of spring.  Below are the six scope values can be used in spring:

  1. singleton 

  2. prototype 

  3. request 

  4. application 

  5. session 

  6. globalSession 

Below table gives example scope identifiers provided by spring:

singleton

org.springframework.beans.factory.config.BeanDefinition.SCOPE_SINGLETON

org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_SINGLETON

prototype

org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE

org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE

request

org.springframework.web.context.WebApplicationContext.SCOPE_REQUEST

application

org.springframework.web.context.WebApplicationContext.SCOPE_APPLICATION

session

org.springframework.web.context.WebApplicationContext.SCOPE_SESSION

globalSession

org.springframework.web.context.WebApplicationContext.SCOPE_GLOBAL_SESSION

 Spring @Scope Annotation Example

package com.java4coding;

 

import org.springframework.beans.factory.config.BeanDefinition;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Scope;

 

import com.java4coding.EmployeeService;

 

@Configuration

public class SpringConfiguration {

        @Bean(name = { "serviceBean", "empService" })

        @Scope(value=BeanDefinition.SCOPE_PROTOTYPE)

        public EmployeeService employeeService() {

                return new EmployeeService(employeeBean());

        }

 

        @Bean()

        @Scope(value=BeanDefinition.SCOPE_PROTOTYPE)

        public Employee employeeBean() {

                return new Employee();

        }

}

 


All Chapters
Author