spring-boot-dependency-injection은(는) 무엇을 하나요?
Spring Boot 프로젝트를 위한 의존성 주입 패턴을 제공합니다. 생성자 우선 설계, 선택적 협력자 처리, 빈 선택 및 와이어링 검증을 포함합니다. 서비스 및 구성 생성 시, 필드 주입 대체 시, 또는 모호하거나 취약한 Spring 와이어링 문제 해결 시 사용하세요.
패턴
생성자 주입 선호
Spring은 생성자 주입을 권장하며, 이 스킬도 이를 따릅니다:
@Service
public class UserService {
private final UserRepository userRepository;
private final NotificationService notificationService;
public UserService(UserRepository userRepository, NotificationService notificationService) {
this.userRepository = userRepository;
this.notificationService = notificationService;
}
}
final 필드는 불변성을 강제하고 순환 의존성을 쉽게 감지할 수 있게 합니다.
선택적 협력자
선택적 의존성은 빈이 없어도 허용됩니다:
@Service
public class ReportingService {
private final AuditService auditService;
public ReportingService(@Autowired(required = false) AuditService auditService) {
this.auditService = auditService;
}
public void generateReport() {
if (auditService != null) {
auditService.log("Report generated");
}
}
}
또는 Optional을 사용합니다:
@Service
public class ReportingService {
private final Optional<AuditService> auditService;
public ReportingService(Optional<AuditService> auditService) {
this.auditService = auditService;
}
}
동일한 유형의 여러 빈
@Service
public class PaymentProcessor {
private final PaymentGateway primaryGateway;
private final List<PaymentGateway> allGateways;
public PaymentProcessor(@Primary PaymentGateway primaryGateway,
List<PaymentGateway> allGateways) {
this.primaryGateway = primaryGateway;
this.allGateways = allGateways;
}
}
@Qualifier를 사용한 명시적 빈 선택
@Service
public class CacheManager {
private final Cache redisCache;
private final Cache localCache;
public CacheManager(@Qualifier("redisCache") Cache redisCache,
@Qualifier("localCache") Cache localCache) {
this.redisCache = redisCache;
this.localCache = localCache;
}
}
와이어링 검증
의존성이 올바르게 주입되었는지 확인합니다:
@Component
public class DependencyValidator {
private final List<DataSource> dataSources;
public DependencyValidator(List<DataSource> dataSources) {
this.dataSources = dataSources;
}
@PostConstruct
public void validate() {
if (dataSources.isEmpty()) {
throw new IllegalStateException("At least one DataSource bean must be defined");
}
}
}
@Configuration
public class AppConfig {
@Bean
@ConditionalOnMissingBean
public DataSource defaultDataSource() {
return new EmbeddedDatabaseBuilder().build();
}
}
효과적인 DI를 위한 단계
- 생성자 주입 사용: 필요한 의존성에
final필드와 생성자 주입을 사용합니다. - 유연성을 위해 선택적 협력자: 선택적 협력자에
@Autowired(required = false)또는Optional을 사용합니다. - 여러 빈 처리: 동일한 유형의 여러 빈 처리에
@Primary,@Qualifier, 또는List<T>주입을 사용합니다. - 와이어링 검증:
@PostConstruct또는@ConditionalOnMissingBean을 사용하여 의존성 만족 여부를 검증합니다. - 필드 주입 방지: 테스트 가능성과 명시적 계약 관리를 위해 생성자 주입을 선호합니다.