스파르타 코딩 클럽 | 자바 심화 과정/Spring Master (입문 주차)
IoC Container와 Bean
luminous_dev
2025. 1. 26. 18:04
@Controller, @RestController, @Service, @Repository .. 이것들이 모두 Bean이다.
Bean (빈) : Spring이 관리하는 객체
Spring IoC 컨테이너: 'Bean'을 모아둔 컨테이너
'Bean' 아이콘 확인 → 스프링 IoC 에서 관리할 'Bean' 클래스라는 표시
@ComponentScan
- Spring 서버가 뜰 때 @ComponentScan에 설정해 준 packages 위치와 하위 packages 들을 전부 확인하여 @Component가 설정된 클래스들을 ‘Bean’으로 등록 해줍니다.
@Configuration
@ComponentScan(basePackages = "com.sparta.memo")
class BeanConfig { ... }
Spring 'Bean' 사용 방법
1. @Autowired
: Spring에서 IoC 컨테이너에 저장된 memoRepository ‘Bean’을 해당 필드에 DI 즉, 의존성을 주입해주는 것
: 사용할 메서드 위에 작성
: 객체의 불변성을 확보할 수 있기 때문에 일반적으로는 생성자를 사용하여 DI하는 것이 좋음
: set… Method를 만들고 @Autowired를 적용하여 DI 할 수도 있음
@Component
public class MemoService {
private final MemoRepository memoRepository;
@Autowired
public MemoService(MemoRepository memoRepository) {
this.memoRepository = memoRepository;
}
// ...
}
* Spring 4.3버전부터 생략 가능, 생성자 선언이 1개일 때만
생략 가능
public class A {
public A(B b) { ... }
}
생략 불가
public class A {
@Autowired // 생략 불가
public A(B b) { ... }
@Autowired // 생략 불가
public A(B b, C c) { ... }
}
2. @RequiredArgsConstructor (@Autowired 대신 사용 가능)
@Component
@RequiredArgsConstructor // final로 선언된 멤버 변수를 파라미터로 사용하여 생성자를 자동으로 생성합니다.
public class MemoService {
private final MemoRepository memoRepository;
// public MemoService(MemoRepository memoRepository) {
// this.memoRepository = memoRepository;
// }
...
3. ApplicationContext
: BeanFactory등을 상속하여 기능을 확장한 Container
: BeanFactory - ‘Bean’ 의 생성, 관계설정등의 제어를 담당하는 IoC 객체
스프링 IoC 컨테이너에서 ‘Bean’을 수동으로 가져오는 방법
@Component
public class MemoService {
private final MemoRepository memoRepository;
public MemoService(ApplicationContext context) {
// 1.'Bean' 이름으로 가져오기
MemoRepository memoRepository = (MemoRepository) context.getBean("memoRepository");
// 2.'Bean' 클래스 형식으로 가져오기
// MemoRepository memoRepository = context.getBean(MemoRepository.class);
this.memoRepository = memoRepository;
}
...
}
Spring 3 Layer Annotation
: Controller, Service, Repository의 역할
Spring 3 Layer Annotation은 모두 @Component가 추가되어있음