@Scope – How to get Scope of Bean from Code

@Scope – How to get Scope of Bean from Code

When we create a Bean we are creating  actual instances of the class defined by that bean definition. We can also control the scope of the objects created from a particular bean definition.

There are 5 types of scopes in bean,

  • singleton (default scope)
  • prototype
  • request
  • session
  • global-session

Singleton:
Single instance per spring IoC container

Prototype:
Single bean definition to any number of object instances.

Request:
Bean definition for each request. Only valid web-aware Spring ApplicationContext.

Session:
Bean definition for a session. Only valid web-aware Spring ApplicationContext.

Global-Session:
Similar to session but the only makes sense in the context of portlet-based web applications. Only valid web-aware Spring ApplicationContext.

In this example, we are going to see how can we get the Scope of bean through java code. We are going to create two bean classes – Employee and Student

Employee is Singleton and Student is Prototype.

Now let us see how to get these scope of bean through Java code.

 

pom.xml

Employee.java

Student.java

ScopeService.java

ScopeController.java

App.java

application.properties

home.jsp

Output:

From output we can see,
@org.springframework.context.annotation.Scope(proxyMode=DEFAULT, value=singleton, scopeName=) 

scopeName and value are aliases, we cant mention both together.

If we try to mention both, we will get the exception

Example:
@Scope(value=”singleton”, scopeName=”ScopeName”)

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.javainfinite.App]; nested exception is org.springframework.core.annotation.AnnotationConfigurationException: In AnnotationAttributes for annotation [org.springframework.context.annotation.Scope] declared on class ‘com.javainfinite.model.Employee’, attribute ‘value’ and its alias ‘scopeName’ are declared with values of [singleton] and [ScopeName], but only one is permitted.
But we can use either one @Scope(value=”singleton”) or @Scope(scopeName=”singleton”)

Download code here

 

 

 

Read More