1. 일반 Java에서는 내가 new한다
UserRepository repository = new UserRepository();
UserService service = new UserService(repository);
UserController controller = new UserController(service);
내가 직접 객체를 만들고, 필요한 객체도 직접 넣어준다.
2. 생성자
public UserService(UserRepository repository) {
this.repository = repository;
}
뜻:
UserService를 만들려면 UserRepository가 필요하다.
즉 생성자는 객체가 만들어질 때 필요한 것을 받는 통로다.
3. DI
DI는:
필요한 객체를 직접 new하지 않고 외부에서 받아 사용하는 것
이다.
public UserService(UserRepository repository) {
this.repository = repository;
}
여기서 UserService가 UserRepository를 직접 만들지 않고 밖에서 받기 때문에 DI 구조다.
4. Spring에서는 new를 Spring이 대신한다
@Repository
public class UserRepository {
}
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
}
@Controller
public class UserController {
private final UserService service;
public UserController(UserService service) {
this.service = service;
}
}
개발자가 직접
new UserRepository();
new UserService(repository);
new UserController(service);
하지 않는다.
Spring이:
UserRepository 생성
↓
UserService 생성
→ Repository 주입
↓
UserController 생성
→ Service 주입
을 대신한다.
5. Bean
Spring이 생성하고 관리하는 객체 = Bean
따라서 위의:
UserRepository → Bean
UserService → Bean
UserController → Bean
이다.
6. @Component
@Component
public class UserService {
}
뜻:
"Spring아, 이 클래스를 네가 객체로 만들어서 Bean으로 관리해."
@Service, @Repository, @Controller도 결국 Spring이 관리하는 Bean으로 등록되는 계열이다.
@Component
@Service
@Repository
@Controller
↓
Spring이 객체 생성
↓
Bean
7. @Bean
@Bean
public GameCharacter createCharacter() {
return new GameCharacter();
}
여기서 createCharacter()는 메서드다.
메서드가 실행되면:
createCharacter()
↓
new GameCharacter()
↓
객체 반환
↓
Spring이 그 객체를 Bean으로 관리
즉:
@Bean = 내가 객체를 만드는 레시피를 작성하고, 만들어진 객체를 Spring에게 관리시킨다.
@Component와 @Bean의 차이는 사용법이 아니라 Bean을 등록하는 방법이다.
@Component
→ 클래스를 보고 Spring이 생성
@Bean
→ 내가 메서드에서 생성 방법을 작성
→ 반환된 객체를 Spring이 관리
8. @Autowired
생성자가 하나라면 보통:
public UserService(UserRepository repository) {
this.repository = repository;
}
만 써도 Spring이 이 생성자를 사용해서 UserRepository를 주입한다.
생성자가 여러 개라서 특정 생성자를 주입 대상으로 지정해야 하는 경우 @Autowired를 사용할 수 있다.
@Autowired
public UserService(UserRepository repository) {
this.repository = repository;
}
9. 같은 타입의 Bean이 여러 개라면
예를 들어:
GameCharacter Bean A
GameCharacter Bean B
둘 다 GameCharacter 타입이면 Spring이 어떤 것을 넣어야 할지 모를 수 있다.
그때:
@Qualifier("newbieCharacter")
GameCharacter character
처럼 원하는 Bean을 지정한다.
전체 흐름
일반 Java
내가 new
↓
객체 생성
↓
내가 직접 연결
Spring
클래스 발견
↓
Spring이 new
↓
Bean으로 관리
↓
필요한 Bean을 생성자에 주입
↓
객체들이 연결됨
핵심 5줄
생성자 = 객체가 만들어질 때 필요한 것을 받는 통로
DI = 필요한 객체를 밖에서 넣어주는 것
Bean = Spring이 관리하는 객체
@Component = 클래스를 보고 Spring이 Bean 생성
@Bean = 내가 만든 객체를 Spring Bean으로 등록
결국 Spring의 핵심은 new 자체가 없어지는 게 아니라, Bean으로 관리할 객체의 생성과 연결을 Spring이 대신한다는 것이다.
'JAVA Spring Boot' 카테고리의 다른 글
| Spring 빈 생명주기와 Unity 생명주기 비교 (0) | 2026.09.15 |
|---|---|
| Java와 C#의 타입과 객체 차이 정리 (0) | 2026.09.01 |