∎ 싱글톤 패턴의 필요
웹에서 객체 생성을 계속 요청하면 JVM에 메모리 낭비가 심해지므로, 싱글톤 패턴이 되도록 한다.
자바의 싱글톤 문법 다시보기!
public class 클래스 { private static 클래스 singleton = new 클래스(); private 클래스() {} //생성자 public static 클래스 getInstance() { return singleton; } }
- static으로 선언해 전역변수로서 프로그램이 끝날때까지 heap영역에 존재하도록 한다.
- 메소드를 통해 객체에 접근하도록 하여 "한개의 객체"를 여러번 사용하도록 유도한다.
- 생성자까지 private하여 접근을 완벽히 막는다.
클래스 변수1 = 클래스.getInstance(); 클래스 변수2 = 클래스.getInstance();
- 변수1과 변수2는 같은 객체를 공유한다.
∎ 스프링 컨테이너 (싱글톤 컨테이너)
싱글톤의 여러가지 문제점을 해결하면서 사용할 수 있게 해준다.
- @Bean이 대표적으로 싱글톤으로 되어있다.
- 싱글톤 패턴을 직접 작성하지 않아도 되기 때문에 DIP, OCP를 위반하지 않을 수 있다.
생성하는 법
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
- 컨테이너를 생성하면 @Bean들이 전부 등록된다.
- 각각의 @Bean들의 의존관계가 등록된다.
AppConfig.class
Bean들의 Type은 인터페이스로 한다. ➜ 역할을 명시하기 위해
주의점!!
- 값을 변경할 수 있는 필드가 있으면 안된다.
- 읽기만 가능하도록 하고, 공유되지 않는 지역변수나 파라미터나 ThreadLocal 등을 활용하도록 한다.
➜ 객체의 상태를 항상 유지시켜야 한다.
- 빈을 등록할 때에도 @Configuration가 객체의 중복 생성을 막아준다.
- 수많은 빈을 자동으로 등록해주는 @ComponentScan이 있다.
- 컨포넌트 스캔을 하기위해선 각 클래스마다 @Component를 붙여줘야 한다.
- 의존 관계는 클래스 안에 @Autowired를 붙여 설정해준다.
- @Component 클래스들이 저장소에 등록되어 있고, @Autowired는 그 중 타입이 같은 것을 찾아 의존 관계를 맺어준다.
- @Component, @Controller, @Service, @Repository, @Configuration을 사용하면 모두 빈으로 자동 등록된다. (컴포넌트 스캔)
'Spring' 카테고리의 다른 글
의존성 주입 원칙 (0) | 2024.08.10 |
---|---|
Junit - 테스트 코드 (0) | 2024.08.10 |