Spring Framework 에서 Bean의 범위를 정의하는데 사용됨
이 어노테이션을 통해 Bean 이 생성되고 관리되는 범위(라이프 사이클)를 설정할 수 있음. 기본적으로 Spring은 모든 빈을 싱글턴으로 관리하지만,@Scope어노테이션을 사용하여 빈의 범위를 다양하게 조정할 수 있음
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.scope;
@Configuration
public class AppConfig {
@Bean
@Scope("prototype")
public MyService myService() {
return new MyService();
}
}
MyService 빈의 범위를 prototype 으로 설정함.
이는 MyService 빈이 요청될 때마다 새로운 인스턴스가 생성된다는 것을 의미함.
singleton(기본값)@Scope("singleton") 또는 @Scope 어노테이션을 생략할 경우 기본값임.prototype@Scope("prototype")request@Scope("request")session @Scope("session")applicationsingleton 과 유사하지만, 애플리케이션 컨텍스트가 아니라 서블릿 컨텍스트 기준임.@Scope("application")websocket@Scope("websocket")prototype 범위는 빈이 매번 새로 생성되므로, 메모리 사용량과 성능에 영향을 줄 수 있음prototype 범위의 빈은 주입할 때마다 새로운 인스턴스가 제공되므로, @Autowired 로 주입받을 때 관리가 어려울 수 있음. 이 경우, @Lookup 메서드 주입을 사용하는 방법도 고려할 수 있음