Key line overrides @ autowired / @ Inject Map <String, Object>?
I have several Spring beans of type CustomerApiLink, let's say the name of these beans is "ableCustomer", "bravoCustomer" and "charlieCustomer" respectively (this is just an example). Now I insert them all into the card through
//DI through annotation @Inject private Map<String,CustomerApiLink> apis; But I found that by default, the Spring IoC container always uses its name as the map key, I want to override this to get the map:
able-> bean ref = "ableCustomer";
bravo-> bean ref = "bravoCustomer";
charlie-> bean ref = "charlieCustomer";
Can this be done with annotation? Or do I need to create another bean utility in an XML file?
I have done this several times. Usually I @Inject a Set object I want for the constructor or setter, and create a Map at this point.
public class MyObject { private Map<String, CustomerApiLink> apiLinks; @Inject public MyObject(Set<CustomerApiLink> apis) { apiLinks = new HashMap<String, CustomerApiLink>(); for(CustomerApiLink api : apis) { apiLinks.put(api.getName(), api); } } } Of course, with this solution, you need a way to get the key to the CustomerApiLink object. In this case, I assumed that the getName() method would exist.
XML is not needed, but you can annotate the setter method instead of a field and process the provided map yourself in this method.
@Inject public void setApis(Map<String,CustomerApiLink> apis){ this.apis = new HashMap<String,CustomerApiLink>(); // now copy values from the incoming map to your internal map // using keys of your own choice } private Map<String,CustomerApiLink> apis;