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:

Following code shows how to use prototype scope:

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

Cricket_Coach.java

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

applicationContext.xml

App.java

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

Cricket_Coach.java

applicationContext.xml

App.java

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

Pin It on Pinterest

Share This