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 – Annotation-based Inversion of Control (IoC)

Spring – Annotation-based Inversion of Control (IoC) We have previously discussed an example of Spring IoC (Inversion of Control). In the previous case, we have used the bean-configuration file to define the bean...

3 minutes read.

Spring – Bean Lifecycle

Spring – Bean Lifecycle Spring bean is responsible for managing the lifecycle of beans created by the Spring container.  The lifecycle of the bean is easy to understand. When a bean is created, it requires...

4 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 Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in...

2 minutes read.

Spring MVC Tutorial

Spring MVC is a web Model-View-Controller framework built on Servlet API. It is used to build web applications. The MVC framework works around central servlet called DispatcherServlet. It dispatches the requests to the...

4 minutes read.

Spring - Bean lifecycle using annotations

Spring - Bean lifecycle using annotations We have already discussed the bean lifecycle using an XML-based configuration. In the previous case, we have declared the init-method and destroy-method attributes in the bean-configuration file. Here, we...

2 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 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 Autowiring – Setter Injection

Spring Autowiring – Setter Injection We have previously discussed an example of Setter Dependency Injection (SDI) using an XML file. In the previous case, we have defined the property name for the dependency...

2 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 - 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 MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same...

12 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 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 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 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 – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 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 - 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 – 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.