Java Spring 프레임워크의 핵심 요소인 Bean에 대해 깊이 있게 알아보도록 하겠다. Spring을 사용하면서 Bean이 어떻게 동작하고, 왜 중요한지 이해하는 것은 매우 중요하다.
1. Bean이란 무엇인가?
Spring에서 Bean은 Spring IoC(Inversion of Control) 컨테이너가 관리하는 객체를 의미한다. 일반적인 Java 객체지만, Spring 컨테이너에 의해 생성되고, 의존성 주입 등의 생명주기 관리를 받는다.
- IoC 컨테이너: 객체의 생성부터 소멸까지의 생명주기를 관리하고, 필요한 의존성을 주입해주는 역할을 한다.
2. Bean의 등록 방법
2.1 어노테이션 기반 등록
- @Component: 일반적인 컴포넌트를 나타낼 때 사용한다.
- @Controller: MVC 패턴에서 컨트롤러 역할을 하는 클래스에 사용한다.
- @Service: 비즈니스 로직을 처리하는 서비스 클래스에 사용한다.
- @Repository: 데이터 접근 계층을 나타낼 때 사용한다.
@Component
public class MyComponent {
// ...
}
2.2 자바 설정 파일 사용
- @Configuration과 @Bean 어노테이션을 활용하여 Bean을 등록한다.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
2.3 XML 설정 파일 사용
- XML 파일에 Bean을 직접 등록하는 방법
<beans>
<bean id="myService" class="com.example.MyService"/>
</beans>
3. Bean의 생명주기
Bean은 생성부터 소멸까지 특정한 생명주기를 가진다.
- 인스턴스화: Bean 객체가 생성된다.
- 의존성 주입: 필요한 의존성들이 주입된다.
- 초기화 콜백: 커스텀 초기화 메서드가 호출된다.
- 사용: Bean이 애플리케이션에서 사용된다.
- 소멸 전 콜백: Bean이 소멸되기 전에 정리 작업을 수행한다.
3.1 초기화와 소멸 메서드 지정
@Component
public class MyBean {
@PostConstruct
public void init() {
// 초기화 로직
}
@PreDestroy
public void destroy() {
// 소멸 전 로직
}
}
4. Bean의 스코프(Scope)
Bean의 스코프는 Bean이 생성되고 유지되는 범위를 정의한다.
4.1 기본 스코프
- Singleton: (기본값) 애플리케이션 컨텍스트당 하나의 인스턴스만 존재한다.
4.2 기타 스코프
- Prototype: 요청 시마다 새로운 인스턴스가 생성된다.
- Request: HTTP 요청당 하나의 인스턴스가 생성된다.
- Session: HTTP 세션당 하나의 인스턴스가 생성된다.
- Application: 서블릿 컨텍스트당 하나의 인스턴스가 생성된다.
- WebSocket: WebSocket 세션당 하나의 인스턴스가 생성된다.
@Component
@Scope("prototype")
public class PrototypeBean {
// ...
}
5. 의존성 주입(Dependency Injection)
Bean 간의 의존 관계를 설정하여 결합도를 낮추고 유연성을 높일 수 있다.
5.1 생성자 주입 (권장)
@Component
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
5.2 세터 주입
@Component
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}
}
5.3 필드 주입 (비권장)
@Component
public class MyService {
@Autowired
private MyRepository myRepository;
}
주의: 필드 주입은 테스트 및 유지보수에 불리하므로 생성자 주입을 권장
6. Bean의 활용 예시
6.1 서비스 계층 구성
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findUser(Long id) {
return userRepository.findById(id);
}
}
6.2 컨트롤러에서의 사용
@RestController
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findUser(id);
}
}
7. 결론
Spring의 Bean은 애플리케이션의 구성 요소를 체계적으로 관리하고, 의존성 주입을 통해 결합도를 낮춰준다. Bean의 개념과 활용 방법을 잘 이해하면 더욱 효율적이고 유지보수성이 높은 애플리케이션을 개발할 수 있다.
'Back-end > Spring' 카테고리의 다른 글
[Spring] Spring에서의 예외 처리 (0) | 2024.07.10 |
---|---|
[Spring] @Transactional (0) | 2024.05.11 |
[Spring] @Annotation (0) | 2024.03.13 |
[Spring] Model 객체 (0) | 2024.03.12 |