Question Details

No question body available.

Tags

java spring spring-bean

Answers (2)

Accepted Answer Available
Accepted Answer
September 8, 2025 Score: 5 Rep: 127,136 Quality: Expert Completeness: 80%

You are basically asking multiple questions in a single question.

  • Is there a Spring feature or pattern that allows me to autowire a Map automatically?

No there isn't. Although you could improve on your @Bean method by injecting a List and expose it as a Map. But that is all the Spring can do for you.

@Bean
public Map paymentServicesMap(List services) {
  var servicesMap = new HashMap();
  for (var service : services) {
    var annot = AnnotationUtil.getAnnotation(PaymentType.class, service.getClass());
    servicesMap.put(annot, service);
  }
  return servicesMap;
}
  • Can I avoid manually building the map in an @Bean method?

No. Spring by default can inject a Collection or a Map, where the collection will contain all beans of that type and the map will contain the name and the service.

  • Are there best practices for wiring multiple service implementations in this way?

As mentioned above only for collections and a specific type of map.

September 8, 2025 Score: 4 Rep: 2,861 Quality: Medium Completeness: 60%

Consider adding a method to the PaymentService:

PaymentType getPaymentType();

Multiple implementations will be available as an injectable List. So the configuration can then be simplified to:

@Configuration
public class PaymentConfiguration {

@Bean public Map getPaymentServices(final List paymentServices) { // or AbstractPaymentService return paymentServices.stream() .collect(Collectors.toMap(PaymentService::getPaymentType, Function.identity())); }

}

where a PaymentService implementation is managing itself.

Having a public getPaymentType() might be a little awkward, so there could be an AbstractPaymentService with an abstract public getPaymentType() as the base class for each implementation. But this would require the configuration to be in the same package as the abstract class.