Issue
I've a simple question.(odd scenario for me)
I've this bean below.
@Configuration
public class ConfigurationBean {
@Bean
public Config getConfig() {
return ConfigFactory.load();
}
@Bean
public Map<String, String> tableMap(Config config) {
return config.getObject("tables").unwrapped().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString()));
}
@Bean
public String url(Config config) {
return config.getString("url");
}
}
And my service class;
@Component
public class TableService {
private final Map<String, String> tableMap;
private final String url;
private Connection connection;
private final TableToJsonConverter tableToJsonConverter;
@Autowired
public TableService(TableToJsonConverter tableToJsonConverter,
String url,
Map<String, String> tableMap) {
this.url = url;
this.tableMap = tableMap;
this.tableToJsonConverter = tableToJsonConverter;
}
So the scenario is,
url
bean returns value www.google.com
.
tableMap
bean returns newGame:new_game_table,oldGame:old_game_table
Now what I am expecting to inject map to map, string to string in the constructor of TableService
. But what really happens is, url
is inserted correctly however the map is injected as url:www.google.com
I am a bit puzzled, could you please let me know what's happening here?
Thanks in advance.
Solution
That is expected behavior. Spring supports taking collection types to pass in multiple beans. So List<MyPojo>
will inject a list of all the MyPojo beans. What is happening in your case, is Spring is injecting the bean name / string value since that is a Map<String, String>
.
You shouldn't have to name beans though, the default bean name is the method name. The qualifier is a valid workaround in this case.
Answered By - SledgeHammer
Answer Checked By - Mildred Charles (JavaFixing Admin)