Spring @Scope Annotation Example

In this section we will learn about @Scope Annotation

The scope of a bean defines the life cycle and visibility of that bean in the contexts in which it is used. A bean’s scope is set using the @Scope annotation. 

Singleton scope is the default scope in spring. Means, the Spring framework creates exactly one instance for each bean declared in the IoC container.

The scopes supported out of the box are listed below:


The last three scopes mentioned request, session, and globalSession are only available in a web-aware application.

We use @Scope to define the scope of a @Component, @Service, and @Repository class or a @Bean definition.


1. Use @Scope to define the scope of a @Service.

@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
//@Scope(value="prototype")
public class EmailService implements MessageService{

private String message;

@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}
}


2. Use @Scope to define the scope of @Bean definition.

@Configuration
public class AppConfig {

@Bean(name="smsService")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MessageService smsService() {
return new SMSService();
}
}


The following example creates a Spring Boot application which uses @Scope annotation and a prototype scope. We will demonstrate this example using Annotation based (@Service) as well as Java-based configuration(@Bean).

Project Directory



pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-scope-annotation-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-scope-annotation-example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


MessageService.java

package com.knf.dev.demo.service;

public interface MessageService {

String getMessage();

void setMessage(String message);
}


EmailService.java

package com.knf.dev.demo.service;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
//@Scope(value="prototype")
public class EmailService implements MessageService{

private String message;

@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}
}


SMSService.java

package com.knf.dev.demo.service;

public class SMSService implements MessageService{

private String message;
@Override
public String getMessage() {
return message;
}

@Override
public void setMessage(String message) {
this.message = message;
}
}


AppConfig.java

package com.knf.dev.demo.config;

import com.knf.dev.demo.service.MessageService;
import com.knf.dev.demo.service.SMSService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class AppConfig {

@Bean(name="smsService")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MessageService smsService() {
return new SMSService();
}
}


Run the application - Application.java

package com.knf.dev.demo;

import com.knf.dev.demo.service.EmailService;
import com.knf.dev.demo.service.MessageService;
import com.knf.dev.demo.service.SMSService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(Application.class, args);

//Example using Annotation based (@Service) configuration
MessageService emailService = context.
getBean(EmailService.class);
emailService.
setMessage("EmailMessageService Implementation");
System.out.println(emailService.getMessage());

MessageService emailService1 = context.
getBean(EmailService.class);
System.out.println(emailService1.getMessage());


//Example using Java-based configuration
MessageService smsService = (MessageService) context.
getBean("smsService");
smsService.
setMessage("SMSMessageService Implementation");
System.out.println(smsService.getMessage());

MessageService smsService1 = (MessageService) context.
getBean("smsService");
System.out.println(smsService1.getMessage());

context.close();
}
}

Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.

Let's run this Spring boot application from either IntelliJ IDEA IDE by right click - Run 'Application.main()'
Or you can use the below maven command to run:

mvn spring-boot:run

Console Output:
EmailMessageService Implementation
null
SMSMessageService Implementation
null


Download Source Code

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete