Spring Boot @Bean Mapvs automatic Map injection behaving differently across 2 seperate project

3 weeks ago 12
ARTICLE AD BOX

Question:

I’m seeing different behavior in two Spring Boot applications regarding Map<String, T> injection.

I have this configuration:

@Bean public Map<String, ChargingGateway> handlerMap() { return new HashMap<>(); }

And this injection point:

public DocumentController(Map<String, ChargingGateway> handlerMap) { this.handlerMap = handlerMap; }

There are multiple implementations of ChargingGateway:

@Component("ab") class AbGateway implements ChargingGateway {} @Component("cd") class CdGateway implements ChargingGateway {}

Expected behavior: If bean handlerMap exists and returns an empty HashMap, I expect that empty map to be injected. If I remove the @Bean, Spring should inject a map containing all ChargingGateway beans (automatic collection injection).

What actually happens: In Application A:

If bean handlerMap is present → injected map is empty. If I remove it → injected map contains all ChargingGateway beans. (This matches expectations.)`

Spring version 3.4.4

In Application B:

With bean handlerMap → injected map is populated. Without it → injected map is also populated. (No observable difference.)`

Spring Version 3.2.2

In both applications:

Constructor injection is used @Bean method name and constructor parameter name are both handlerMap No @Qualifier or @Primary ChargingGateway implementations are regular @Component

The map is effectively an entry point. If it were empty, the application would fail at runtime. However, in production it works fine in both cases.

Question:

Under what conditions would Spring choose the automatically constructed Map<String, T> (containing all T beans) instead of an explicitly defined @Bean Map<String, T>?

Could this be affected by:

Constructor parameter name metadata (-parameters) Different compilation settings between the two applications @Bean resolution precedence rules

I’m trying to understand the exact dependency resolution mechanism that explains the different behavior between the two applications.`

Note: Im pretty sure of in application B the map is not loaded by anything.

Read Entire Article