За кулисами весеннего аутовизированияJAVA

Программисты JAVA общаются здесь
Anonymous
За кулисами весеннего аутовизирования

Сообщение Anonymous »

Я работаю над приложением Spring Boot, где у меня есть несколько реализаций сервисного интерфейса, и я хочу автоматически провести их в клавишу карты с помощью типа перечисления.public interface PaymentService {
void processPayment();
}
< /code>
@Slf4j
@Service
@PaymentHandler(PaymentType.CREDIT_CARD)
public class CreditCardPaymentService implements PaymentService {

@Override
public void processPayment() {
log.info("CreditCardPaymentService processPayment");
}
}
< /code>
@Slf4j
@Service
@PaymentHandler(PaymentType.VENMO)
public class VenmoPaymentService implements PaymentService {

@Override
public void processPayment() {
log.info("VenmoPaymentService processPayment");
}
}
< /code>
public enum PaymentType {
CREDIT_CARD, VENMO
}
< /code>
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface PaymentHandler {
PaymentType value();
}
< /code>
Currently, I’m manually creating a Map
in a configuration class using the ApplicationContext:
@Configuration
public class PaymentConfiguration {

@Bean
public Map
paymentServicesMap(final ApplicationContext applicationContext) {
return applicationContext.getBeansOfType(PaymentService.class).values().stream()
.flatMap(service ->
Optional.ofNullable(service.getClass().getAnnotation(PaymentHandler.class))
.map(annotation -> Map.entry(annotation.value(), service))
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
}
< /code>
@Component
@RequiredArgsConstructor
public class MyStartupRunner implements CommandLineRunner {
private final Map paymentServices;

@Override
public void run(String... args) {
paymentServices.forEach((paymentType, paymentService) -> paymentService.processPayment());
}
}
< /code>
This approach works, but it feels verbose and manual. I’d like to leverage Spring’s @Qualifier or some other feature to avoid having to define the Map bean explicitly. Ideally, I want Spring to automatically inject a Map without additional boilerplate.
I’ve tried approaches like using @Qualifier on individual beans, but it doesn’t seem to work cleanly when mapping multiple implementations to enum keys.
My question:
  • Is there a Spring feature or pattern that allows me to autowire a Map automatically?
  • Can I avoid manually building the map in a @Bean method?
  • Are there best practices for wiring multiple service implementations in this way?
Any guidance or example implementations would be highly appreciated.

Подробнее здесь: https://stackoverflow.com/questions/797 ... autowiring

Вернуться в «JAVA»