Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Injecting a HashMap<Class, List<X>> from XML

Tags:

spring

Right now, I have a class called A that contains an attribute like this one:

private Map<Class<?>, List<EntityIndexConfig>> relatedEntitiesMap;

My initial idea was to inject a few keys with their respective list from the XML but could not make it work. Instead I created a method with @PostConstruct:

@PostConstruct @SuppressWarnings("serial")
public void loadRelatedEntities() {
   /* And here I load it */
   relatedEntitiesMap = new HashMap<Class<?>, List<EntityIndexConfig>>(){{
       put(Agency.class, new ArrayList<EntityIndexConfig>() {{
           add(new EntityIndexConfig("Package.listByAgency", applicationContext.getBean(PackageRepository.class), "agencyId"));
       }});
       /* More entries here... */
   }
}

Despite it works, I would like to be able to have this configuration in the Spring XML file if possible. Any ideas how to create a Map and put classes as keys and a list of EntityIndexConfig?s?

If any of you knows I would appreciate the help. Thanks.

like image 726
Agustin Lopez Avatar asked Jan 24 '26 18:01

Agustin Lopez


1 Answers

As described here in the documentation:

<util:map key-type="java.lang.Class">  
        <entry key="com.MyClass">  
            <util:list>  
              <ref bean="EntityIndexConfig1"/>  
              <bean class="com.mypackage.SomeEntityIndexConfig/>  
            </util:list>  
        </entry> 
</util:map> 

This assumes you have declared the util namespace prefix:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

Please keep in mind I wrote this freehand, and it is quite possible I made a typo or syntax error somewhere. But this should get you very close at least.

like image 93
Vidya Avatar answered Jan 27 '26 07:01

Vidya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!