강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

알고리즘가즈앙님의 프로필 이미지
알고리즘가즈앙

작성한 질문수

[재질문]count1과 count2가 값이 다른이유

작성

·

51

0

@Test
void singletonClientUsePrototype(){
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class,ClientBean.class);
    ClientBean clientBean1 = ac.getBean(ClientBean.class);
    int count1 = clientBean1.logic();
    assertThat(count1).isEqualTo(1);

    ClientBean clientBean2 = ac.getBean(ClientBean.class);
    int count2 = clientBean2.logic();
    assertThat(count2).isEqualTo(2);

    assertThat(clientBean1).isEqualTo(clientBean2);
    System.out.println("clientBean1 = " + clientBean1);
    System.out.println("clientBean2 = " + clientBean2);
    System.out.println("count1 = " + count1);
    System.out.println("count2 = " + count2);
}

전질문: clienBean1=clientBean2는 싱글톤으로 같은걸 알았는데

왜 count1과 count2는 값이 다른건가요?? count1에서 count2는 공유가되서 2가 되었는데 count2에서 count1은 공유가 안된건가요?

에대한 답변으로

ClientBean 내부의 카운트 값은 clientBean2.logic()이 호출되었을때 2로 변경되었을 것입니다. 그러나 count1 값은 두번째 로직이 실행되기 이전에 미리 값을 받아 저장해두었으므로, count1과 count2를 서로 다른 값을 저장하고 있습니다.

이렇게 전달받았는데

clienBean1과 clientBean2는 싱글톤으로 같은 주소를 바라보는데

count1과 count2도 같은 주소에 같은 변수를 가르키는게 아닌가요????

그래서 count2가 2가 되는거이고

그러므로 같은 주소인 count1ㄷ도 2가 되는게 아닌가요?

답변 1

0

안녕하세요, 인프런 AI 인턴입니다.

알고리즘가즈앙님, 질문해주신 C# 코드는 의존성 주입과 스코프(싱글톤/프로토타입)과 관련된 내용입니다. ClientBean, PrototypeBean과 관련된 테스트 코드에서 왜 count1count2가 다른 값을 가지는지 궁금해 하시는 것 같은데요.

먼저, ClientBeanPrototypeBean의 정의가 명확하지 않아서 일반적으로 Spring에서의 동작을 설명드리겠습니다.

Spring에서 PrototypeBean이 프로토타입 스코프로 정의되어 있고 ClientBean이 싱글톤이라면, ClientBean이 생성될 때 PrototypeBean의 새 인스턴스를 사용하게 됩니다. clientBean1clientBean2가 같은 싱글톤 인스턴스를 가리킴에도 불구하고 PrototypeBean의 인스턴스가 다르게 관리되기 때문에 이런 현상이 발생할 수 있습니다.

코드는 예를 들어,

@Component
@Scope("singleton")
public class ClientBean {
    @Autowired
    private PrototypeBean prototypeBean;

    public int logic() {
        return prototypeBean.incrementAndGetCount();
    }
}

@Component
@Scope("prototype")
public class PrototypeBean {
    private int count = 0;

    public int incrementAndGetCount() {
        return ++count;
    }
}

라고 가정했을 때, 테스트 메서드를 실행하면 각 logic() 호출 시 각각 새로운 PrototypeBean 인스턴스가 사용됩니다.

따라서:
1. clientBean1.logic()을 호출하면 prototypeBean의 새로운 인스턴스가 생성되어 incrementAndGetCount() 호출 후 count는 1이 됩니다.
2. clientBean2.logic()을 호출하면 또 다른 새로운 prototypeBean 인스턴스가 생성되어 incrementAndGetCount() 호출 후 count는 1이 됩니다.

이로 인해 count1은 1이고, count2는 1이 되며, 둘 다 동일한 아닌 다른 인스턴스의 count 값을 참조하게 됩니다.

문제는 각 호출이 다른 프로토타입 인스턴스를 사용하여 업데이트하기 때문에 발생합니다. 같은 싱글톤 인스턴스의 메서드를 호출하지만 내부적으로는 다른 프로토타입 인스턴스를 사용하기 때문에 count 값이 다르게 나타납니다.

정확한 코드 구조를 알 수 없으므로, 이런 구조를 참고하시면 도움이 될 듯 합니다.

Spring에서의 작동 원리를 참고할 수 있는 링크도 함께 공유드립니다:
Spring Bean Scopes

이해를 돕기 위한 샘플 코드와 링크를 참고하셔서 문제를 해결해 보시길 바랍니다. 추가 질문이 있으면 언제든지 남겨주세요!

알고리즘가즈앙님의 프로필 이미지
알고리즘가즈앙

작성한 질문수

질문하기