Spring - Bean Scopes with Annotations

Spring - Bean Scopes with Annotations

We have previously discussed the Spring bean scopes using an XML-based configuration. In the XML-based configuration, we have defined the beans and its scope inside the bean-config file (applicationContext).

 Here, we are going to use the @Scope annotation to define the scope of a bean. The @Scope annotation can be used in two ways: as a type-level annotation with @Component or as a method-level annotation with @Bean annotation. The scope defines the lifecycle of an instance. The org.springframework.context.annotation package contains the @Scope annotation.

As we have discussed, there are five scopes in the Spring framework, which are listed below:

  • singleton
  • prototype
  • request
  • session
  • global session

The request, session, and global session are the scopes used with web-aware apps.

Following code shows how to use singleton scope:

@Component
@Scope("singleton")
public class Cricket_Coach implements Coach {
….
} 

Following code shows how to use prototype scope:

@Component
@Scope("prototype")
public class Cricket_Coach implements Coach {
….
}

Example of singleton bean scope

Now, we are going to create an example of a singleton bean scope. In the following example, we have created an interface Coach that contains an unimplemented method. The Cricket_Coach class implements the Coach interface and its unimplemented method.

The singleton scope is the default scope. If we don’t use the @Scope annotation to define the singleton scope, by default Spring will consider it as the singleton scope.

Following are the steps used to create an example of singleton bean scope:

Coach.java

public interface Coach {
public String training();
} 

Cricket_Coach.java

import org.springframework.context.annotation.Scope;
 import org.springframework.stereotype.Component;
 @Component
 @Scope("singleton")
 public class Cricket_Coach implements Coach {
 public Cricket_Coach() {
 System.out.println( "default constructor of Cricket_Coach" ) ;
}
public String training() { 
return "10 rounds of the ground daily..!!" ;
}
} 

In the above class, we have defined the @Scope annotation with the singleton scope just below the @Component annotation.

applicationContext.xml


http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 

App.java

import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App 
{
public static void main( String[] args )
{
ClassPathXmlApplicationContext appcontext = new ClassPathXmlApplicationContext("applicationContext.xml");
// retrieving the beans from the Spring 
Coach coach1 = appcontext.getBean("cricket_Coach" , Coach.class);
Coach coach2 = appcontext.getBean("cricket_Coach", Coach.class);
// check if both the objects are same
boolean result = (coach1 == coach2);
System.out.println("  Check  whether pointing to the same object : " + result);
System.out.println("Memory location for coach1 :  " + coach1);
System.out.println("Memory location for coach1 :  " + coach2);
appcontext.close(); 
}
} 

Output

The following output shows that both the objects are at the same memory location.

output shows that both the objects

Now, we are going to create an example of a prototype bean scope.

Example of prototype bean scope

In the following example, we are going to create an interface Coach which contains an unimplemented method. The Cricket_Coach class implements the Coach interface and its unimplemented methods.

Following are the steps used to create an example of a prototype bean scope:

Coach.java

public interface Coach {
public String training();
} 

Cricket_Coach.java

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class Cricket_Coach implements Coach {
public Cricket_Coach() {
System.out.println( "default constructor of Cricket_Coach" ) ;
}
public String training() { 
return "10 rounds of the ground daily..!!" ;
}
} 

applicationContext.xml


http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 

App.java

import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class App 
 {
public static void main( String[] args )
{
ClassPathXmlApplicationContext appcontext = new ClassPathXmlApplicationContext("applicationContext.xml");
// retrieves beans from the Spring  
Coach coach1 = appcontext.getBean("cricket_Coach" , Coach.class);
Coach coach2 = appcontext.getBean("cricket_Coach", Coach.class);
// check if both the objects are same or not 
boolean result = (coach1 == coach2);

System.out.println("Check whether pointing to the same object : " + result);
System.out.println("Memory location for coach1 : " + coach1);
System.out.println("Memory location for coach1 : " + coach2);
appcontext.close(); 
}
} 

Output

The following output shows that both the objects are at different memory locations.

output shows that both the objects are at different memory locations


Related Topics

Spring Framework Annotations

Spring Framework Annotations Spring framework provides a variety of annotations for a better approach. Using annotations, we can develop Spring applications (small & large scale) easily with less code. Following are the annotations...

6 minutes read.

Spring AOP – @Around Advice

Spring AOP – @Around Advice We have discussed in our previous tutorial, the concepts, and terminology of the Spring AOP. Around advice is one of the types of advices. It can be applied to...

4 minutes read.

Spring MVC Form Text Field

We have previously discussed the Spring MVC form tags. The form tag library provides a variety of form tags that are used to build web applications. One of them is a <form:input>...

8 minutes read.

Spring Autowiring

Spring Autowiring Autowiring is an essential feature of the Spring framework. The autowiring function is used for wiring beans automatically, without injecting the beans using <constructor-arg> and <property> elements in the bean-config file. It can...

3 minutes read.

Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC) The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done...

4 minutes read.

Spring MVC Form Validation

Spring Validation is used to validate the @Controller inputs. It is used to check and accept the user input in any web application. Using Spring validation, we can validate the user input on...

12 minutes read.

Spring MVC Example

Spring MVC Example We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC. Following are the steps used to create an example...

2 minutes read.

Spring MVC Example – Reading HTML Form Data

We have discussed earlier a simple example of Spring MVC in which we have created multiple view pages. Here, we are going to create another Spring MVC example in which we are...

7 minutes read.

Spring Autowiring –Field Injection

Spring Autowiring –Field Injection The Field Injection is used to inject the fields, variables, or properties of the beans. It is not available in autowiring using XML- based configuration. It is a...

2 minutes read.

Spring – Dependency Injection

Spring – Dependency Injection One of the main features of Inversion of Control (IoC) is Dependency Injection (DI). It is a process of supplying the dependencies from one object to others. The Spring-Core container...

8 minutes read.

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring AOP – Pointcut Expressions

Spring AOP – Pointcut Expressions Pointcut refers to a collection of join points that specify where advice to be applied. In other words, pointcut represents a set of various join points. It defines that...

7 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring MVC Form – Radio Button

A variety of form tags are available in Spring MVC for developing web applications, <form:radiobutton> tag is one of them. The radio button tag is used to choose only one option among a...

10 minutes read.

Spring AOP - @AfterThrowing Advice

Spring AOP - @AfterThrowing Advice As we have discussed in our previous tutorial, Advice is one of the essential concepts of the Spring AOP. The after throwing advice is one of the types of...

3 minutes read.

Spring MVC Number Range Validation

Example of Number Range Validation Here, we are going to create an example of number range validation. Following are the steps to create an example of number range validation. Create a request page In this step, we are...

12 minutes read.

Spring Model Interface

Model Interface Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available...

8 minutes read.

Spring - Bean Scopes with Annotations

Spring - Bean Scopes with Annotations We have previously discussed the Spring bean scopes using an XML-based configuration. In the XML-based configuration, we have defined the beans and its scope inside the bean-config...

3 minutes read.

Spring - Injecting values from Property Files

Spring - Injecting values from Property Files In this section, we will discuss how to inject values from a property file using the Java-based configuration. Here, we will use two annotations @Value and @PropertySource...

3 minutes read.

Spring Tutorial

What is Spring Framework? Spring is one of the most popular enterprise application framework used for developing Java applications. “Spring is a lightweight open-source framework. It allows Java developer to build simple, reliable,...

6 minutes read.