티스토리 뷰
싱글톤 방식의 주의점

상태를 유지할 경우 발생하는 문제점 예시*
StatefulService
public class StatefulService {
    private int price; //상태를 유지하는 필드
    
    public void order(String name, int price) {
        System.out.println("name = " + name + " price = " + price);
        this.price = price; //여기가 문제!
    }
    
    public int getPrice() {
        return price;
    }
    
}
상태를 유지할 경우 발생하는 문제점 예시**
StatefulServiceTest
먼저 static클래스 만들어서 빈 등록
// 스태틱 클래스 만들어서 빈 등록
static class TestConfig {
    @Bean
    public StatefulService statefulService() {
        return new StatefulService();
    }
}
전체 코드
package inflearn.spring_core.singleton;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
public class StatefulServiceTest {
    @Test
    void statefulServiceSingleton() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class);
        StatefulService statefulService1 = ac.getBean("statefulService", StatefulService.class);
        StatefulService statefulService2 = ac.getBean("statefulService", StatefulService.class);
        //ThreadA: A사용자 10000원 주문
        statefulService1.order("userA", 10000);
        //ThreadB: B사용자 20000원 주문
        statefulService2.order("userB", 20000);
        //ThreadA: 사용자A 주문 금액 조회
        int price = statefulService1.getPrice();
        //ThreadA: 사용자A는 10000원을 기대했지만, 기대와 다르게 20000원 출력
        System.out.println("price = " + price);
        Assertions.assertThat(statefulService1.getPrice()).isEqualTo(20000);
    }
    // 스태틱 클래스 만들어서 빈 등록
    static class TestConfig {
        @Bean
        public StatefulService statefulService() {
            return new StatefulService();
        }
    }
}
그림으로 설명하면
실행 결과

price = 10000을 기대했으나
price = 20000이 출력되어 나온다!!!!
그림으로 다시 설명하면


문제 해결



728x90
    
    
  반응형
    
    
    
  '[개발] - Spring > 핵심 원리 구현' 카테고리의 다른 글
| @Configuration과 바이트코드 조작의 마법 (0) | 2024.01.29 | 
|---|---|
| @Configuration과 싱글톤 (0) | 2024.01.29 | 
| 싱글톤 컨테이너 (1) | 2024.01.27 | 
| 싱글톤 패턴 (0) | 2024.01.26 | 
| 웹 애플리케이션과 싱글톤 (0) | 2024.01.25 | 
 
                            Comments
                            
                        
                        
                        
                    
                    
                    
                        
                    
                 
                                                     
                                                     
                                                    