Spring에서 객체를 Bean으로 관리하는 이유
●Spring에서 객체를 Bean으로 관리하는 이유
●의존성 관리 자동화
@Service
class OrderService(
private val productRepository: ProductRepository, // 자동 주입
private val paymentGateway: PaymentGateway // 자동 주입
)
●싱글톤 패턴 구현
// 아래 두 userRepository는 동일한 인스턴스
@Service
class UserService(private val userRepository: UserRepository)
@Service
class AuthService(private val userRepository: UserRepository)
●생명주기 관리
@Component
class DatabaseConnection {
@PostConstruct
fun initialize() {
// 초기화 로직
}
@PreDestroy
fun cleanup() {
// 리소스 정리 로직
}
}
●AOP(관점 지향 프로그래밍) 지원
@Service
class TransferService(private val accountRepository: AccountRepository) {
@Transactional // AOP를 통한 트랜잭션 관리
fun transferMoney(from: String, to: String, amount: BigDecimal) {
// 송금 로직
}
}
●테스트 용이성
@SpringBootTest
class UserServiceTest {
@MockBean
lateinit var userRepository: UserRepository
@Autowired
lateinit var userService: UserService
@Test
fun testGetUser() {
// given
val userId = 1L
whenever(userRepository.findById(userId)).thenReturn(User(userId, "Test User"))
// when
val result = userService.getUser(userId)
// then
assertEquals("Test User", result.name)
}
}
●설정의 중앙화
@Configuration
class AppConfig {
@Bean
fun dataSource(): DataSource {
return HikariDataSource().apply {
jdbcUrl = "jdbc:postgresql://localhost:5432/mydb"
username = "user"
password = "password"
maximumPoolSize = 10
}
}
}