빈(Bean)은 스프링 컨테이너(Spring IoC Container)에 의해 관리되는 재사용 가능한 소프트웨어 컴포넌트이다.
즉, 스프링 컨테이너가 관리하는 자바 객체를 뜻하며, 스프링 컨테이너는 하나 이상의 빈(Bean)을 관리한다.
빈은 인스턴스화된 객체를 의미하며, 스프링 컨테이너에 등록된 객체를 스프링 빈이라고 한다.
→ new 키워드 대신 사용한다고 보면 됨.
ExampleService exampleService = new ExampleService()
<bean id="exampleService" class = "com.example.app.ExampleService"/>
- 위의 코드는 new를 통해 exampleService 인스턴스를 만들었다.
- 하지만 xml파일에 빈 태그를 추가하면 exampleService 인스턴스를 스프링 컨테이너가 관리하게 된다.
사용 이유?
스프링이 의존관계를 관리하도록 하는 것에 큰 목적 → 스프링의 특징인 IoC를 통한 DI 주입.
객체가 의존관계를 등록할 때(= 다른 클래스를 사용할 때) 스프링 컨테이너에서 해당하는 빈을 찾고, 그 빈과 의존성을 만든다.
스프링 빈 등록 방법 3가지
- xml에 직접 등록
- 컴포넌트 스캔과 자동 의존관계 설정 → @Component, @Controller, @Service, @Repository, @Autowired
- 자바 코드로 직접 등록 → @Bean
xml에 직접 등록 - 현재는 잘 사용하지 않음.
<bean> 태그 사용
<bean id = "exampleService" class= "com.example.app.ExampleService"/>
컴포넌트 스캔과 자동 의존관계 설정
각 컴포넌트에 해당하는 어노테이션을 붙여주면 된다!
@Component
public class ExampleServiceImpl implements ExampleService{
@Autowired
private ExampleDao exampleDao;
@Override
public int register(ExampleDto exampleDto) {
return exampleDao.register(exampleDto);
}
}
이 어노테이션들을 Stereotype annotation 이라고 하는데 이렇게 나눈 이유는 계층별로 빈의 특성이나 종류를 구분하기 위함이다.
@Repository : DAO 또는 Repository 클래스에서 사용
@Service : Service Layer 클래스에서 사용
@Controller : Presentation Layer의 MVC Controller에서 사용한다.
@Component : Layer를 구분하기 어려운 경우에 사용한다.
마지막으로 @Autowired를 통해 객체 생성 시점에 스프링 컨테이너에서 해당 스프링 빈을 찾아 주입해 준다.
참고로 생성자가 1개만 있을 경우 @Autowired는 생략할 수 있다고 한다.
스프링 3.0부터는 @Inject로 가능하다는데 이건 추후해 정리해보겠다.
자바 코드로 직접 등록
먼저 config 클래스를 만들어준다.
@Configuration
public class ApplicationConfig{
@Bean
public ExampleRepository exampleRepository() {
return new ExampleRepository();
}
@Bean
public ExampleService exampleService() {
return new ExampleService(exampleRepository())
}
}
@Bean 어노테이션을 사용하여 스프링 빈을 생성해준다.
BeanDefinition
어떻게 이렇게 다양하게 Bean을 생성할 수 있을까??? 그것은!
Bean을 설정하는 다양한 방식은 BeanDefinition이라는 추상화 덕분에 가능하다.
스프링 컨테이너는 빈 설정 형식이 XML인지, 어노테이션인지 Java 코드인지 모르며, 바로 이 BeanDefinition만 알면 스프링 빈을 생성할 수 있다.
'Back-end > Server' 카테고리의 다른 글
[Spring] JWT(Json Web Token)란? (0) | 2025.04.06 |
---|---|
[Spring] Spring Security 정리 (0) | 2025.04.06 |
[Spring] 스프링 구조 정리 (0) | 2025.01.11 |
[Server] 웹서버 VS 웹 어플리케이션 서버(WAS) (0) | 2024.06.02 |
[Spring] Spring 프레임워크? (0) | 2024.05.27 |