개발 ━━━━━/Spring(boot)

[Spring] Singleton, Prototype Scope Bean

GukJang 2024. 9. 6. 15:16
반응형

김영한 강사님의 스프링 강의를 보던 중 Singleton, Prototype 에 대한 내용이 나온 적이 있다.

 

ServiceController

@Controller
public class ServiceController {

    private final ApplicationContext context;

    @Autowired
    public ServiceController(ApplicationContext context) {
        this.context = context;
    }

    @GetMapping("/")
    public String getServiceHashes(Model model) {
        SingletonService singletonService = context.getBean(SingletonService.class);
        PrototypeService prototypeService = context.getBean(PrototypeService.class);
        model.addAttribute("singletonHash", singletonService.getMessage());
        model.addAttribute("prototypeHash", prototypeService.getMessage());
        return "hashes";
    }
}

 

PrototypeService

@Service
@Scope("prototype")
public class PrototypeService {
    public String getMessage() {
        return "Prototype instance hash: " + System.identityHashCode(this);
    }
}

 

SingletonService

@Service
public class SingletonService {
    public String getMessage() {
        return "Singleton instance hash: " + System.identityHashCode(this);
    }
}

 

까지 작성을 하고 실행을 시키면

 

같은 결과 값이 뜨는데

새로고침을 해보면

 

Singleton bean 값은 그대로지만

Prototype bean 값은 새로 고침을 할 때 마다 변화하는 것을 확인할 수 있다.

 

Singleton 스코프는 spring 의 기본 스코프로

Spring 컨테이너가 초기화 되는 시점 (어플리케이션이 처음 시작될 때) 에 생성이 되며

bean 을 요청시 항상 같은 인스턴스를 반환한다.

 

Prototype 스코프는 @Scope 어노테이션에 prototype 이라 명시를 해주어야 하고

Singleton 과는 달리 bean 에 대한 요청이 이루어질 때마다 인스턴스를 새로 생성해서 반환을 한다.

컨테이너는 prototype 의 bean 을 생성, 의존성 주입 (DI), 초기화 까지만 관여를 하고 더 이상 관리하지 않는다. ( = destroy 소멸자를 실행하지 않는다.)

 

Singleton 빈 내부에서 Prototype 빈을 의존관계로 주입하는 경우

Prototype 빈이기는 하지만 Singleton 빈 안에 존재하기 때문에 요청이 들어와도 동일한 인스턴스를 반환하게 된다.

 

 

 

참조

https://catsbi.oopy.io/b2de2693-fd8c-46e3-908a-188b3dd961f3

반응형