The @Scope annotation controls how Spring creates and manages instances of a bean. It helps decide if a new object is made each time or if the same one is reused.
@Scope for bean scope in Spring Boot
@Scope("scopeName") public class BeanClass { // bean code }
The scopeName is usually a string like singleton or prototype.
Common scopes include singleton, prototype, request, and session.
@Scope("singleton") public class MyService { // shared instance }
@Scope("prototype") public class MyPrototypeBean { // new instance each time }
@Scope("request") public class MyRequestBean { // one instance per HTTP request }
@Scope("session") public class MySessionBean { // one instance per user session }
This Spring Boot app defines a MessagePrinter bean with prototype scope. When the app runs, it injects two instances of MessagePrinter. Because of the prototype scope, these two instances are different objects. The program prints their references to show they are not the same.
import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") public class MessagePrinter { public void printMessage() { System.out.println("Hello from MessagePrinter instance: " + this); } } import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ScopeExampleApplication implements CommandLineRunner { @Autowired private MessagePrinter printer1; @Autowired private MessagePrinter printer2; public static void main(String[] args) { SpringApplication.run(ScopeExampleApplication.class, args); } @Override public void run(String... args) throws Exception { printer1.printMessage(); printer2.printMessage(); } }
Singleton scope is the default in Spring, meaning one shared instance.
Prototype scope creates a new instance every time the bean is requested.
Web scopes like request and session only work in web-aware Spring contexts.
@Scope controls how many instances of a bean Spring creates.
Use singleton for shared beans and prototype for new instances each time.
Web apps can use request and session scopes for per-request or per-user beans.