[Spring] Singleton, Prototype Scope Bean

2024. 9. 6. 15:16·개발 ━━━━━/Spring(boot)
반응형

김영한 강사님의 스프링 강의를 보던 중 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

반응형

'개발 ━━━━━ > Spring(boot)' 카테고리의 다른 글

[Spring] PDFBox 로 텍스트 추출시 null 값이 추출될 때  (1) 2024.10.10
[Spring] 이전 데이터를 불러올때 stream문과 for문의 성능 차이 테스트 - 1  (1) 2023.11.18
[Spring] WebSocket 을 이용한 채팅 구현  (2) 2023.10.09
[Spring] Entity 관계  (0) 2023.09.02
[Spring] Filter  (0) 2023.09.01
'개발 ━━━━━/Spring(boot)' 카테고리의 다른 글
  • [Spring] PDFBox 로 텍스트 추출시 null 값이 추출될 때
  • [Spring] 이전 데이터를 불러올때 stream문과 for문의 성능 차이 테스트 - 1
  • [Spring] WebSocket 을 이용한 채팅 구현
  • [Spring] Entity 관계
GukJang
GukJang
•  ⌘ ⌥ •
    반응형
  • GukJang
    SPACE
    GukJang
  • 전체
    오늘
    어제
    • Blog (73)
      • 개발 ━━━━━ (68)
        • Java (14)
        • C++ (1)
        • HTML (1)
        • Spring(boot) (7)
        • Dev (9)
        • SQL (1)
        • CS (2)
        • Git (1)
        • Troubleshoot (14)
        • Algorithm (2)
        • Definition (1)
        • Dev Life (2)
        • TIL (7)
        • 항해 (6)
      • 공돌 ━━━━━ (4)
        • 플젝 (2)
        • 장비 (1)
        • 부품 (1)
      • 독서 ━━━━━ (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글쓰기
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    mysql
    spring
    docker volume
    항해99
    Java
    electron-builder
    SpringBoot
    AWS
    docker
    사전 스터디
    마이크로파이썬
    백준
    Python
    알고리즘
    오픈소스 기여
    CI CD
    EC2
    micropython
    자바
    github actions
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
GukJang
[Spring] Singleton, Prototype Scope Bean
상단으로

티스토리툴바