싱글톤#
웹 어플리케이션 특성상, 굉장히 많은 요청이 들어옴 이 때마다 객체가 생성되고 소멸되면, 이는 엄청난 메모리 낭비임
해결책 : 해당 객체가 딱 1개만 생성되고, 공유하도록 설계 => 싱글톤
singleton 예제
private static final SingletonService instance = new SingletonService();
public static SingletonService getInstance(){
return instance;
}
private SingletonService(){
}싱글톤 패턴은 여러가지 문제점을 가지고 있다.
싱글톤 컨테이너#
스프링 컨테이너는, 싱글톤 패턴의 문제점을 해결하면서, 싱글톤 패턴으로 객체 인스턴스를 관리 (Bean)
싱글톤 주의점]#
- **무상태(stateless)**로 설계
- 특정 클라이언트에 의존 ❌
- 특정 클라이언트가 값을 변경 ❌
- 가급적 읽기만 가능
- 필드 대신에 자바에서 공유되지 않는 지역변수, 파라미터, Threadlocal 사용
위 사항을 안지키면, 정말 큰 에러!
@Configuration#
@Bean
public MemberService memberService() {
return new MemberServiceImpl(memberRepository());
}
@Bean
public MemberRepository memberRepository() {
return new MemoryMemberRepository();
}
@Bean
public OrderService orderService() {
return new OrderServiceImpl(memberRepository(), discountPolicy());
}
....이 자바 코드를 보면, 각각 new MemorymemberRepository()를 호출하고 있다.
하지만 이 모든 memberRepository 인스턴스는 같은 객체이다 왜⁉️
바이트 조작#
스프링은 클래스의 바이트코드를 조작하는 라이브러리를 사용한다
@Test
void configurationDeep(){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
AppConfig bean =ac.getBean(AppConfig.class);
System.out.println("bean = " + bean.getClass());
}출력
출럭 : bean = class hello.core.AppConfig$$EnhancerBySpringCGLIB$$ee2b784e
순수한 클래스라면, class hello.core.AppConfig 가 나와야됨
따라서, 스프링이 Appconfig 클래스를 상속받은 임의의 클래스를 만들고, 이를 빈으로 등록한 거임
Appconfig의 @Configuration을 주석처리하면, 순수한 클래스가 등록된다
하지만 싱글톤이 깨짐
따라서, 궁금증을 해결하려는 용도가 아니면 무조건
@Configuration을 사용하자