java - 如何在 Spring 为 map 中未找到的键设置默认值

标签 java spring

我有三个类 a、b 和 c。都继承了同一个类,我必须根据一个键来选择在运行时使用哪个类。

这是我写的Spring代码:

 <bean id="ConfigurationAdapterMap" class="abc">
   <property name="adapterMap">
       <map>
        <entry key="key1">
          <bean class="class1"/>
        </entry>
        <entry key="Other">
          <bean class="class2"/>
        </entry>
      </map>
    </property>     
  </bean>

我不想显式传递“其他”,如果给定键与键集中的任何键都不匹配,我想返回 class2。我可以得到 spring 来做这个吗?

最佳答案

来自文档:

You can also explicitly control the exact type of Map that will be 
instantiated and populated via the use of the 'map-class' 
attribute on the  element.

因此,例如,您可以从 commons-collections 中获取 DefaultedMap 并尝试将其用作 map-class。或者您可以实现自己的 Map 并使用它。

关于java - 如何在 Spring 为 map 中未找到的键设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11733817/

相关文章:

java - 多个JTA事务: no session associated with the current transaction

android - 没有 Maven 的 Android 上的 Spring

java - 调整垃圾回收以实现低延迟

java - 生成两个随机整数并删除它们以防止再次生成

java - 通过for循环将节点添加到面板时出错

java - 在不同的java类中使用已经初始化的类,

java - 错误消息指出 java 的构造函数放错位置

java - 使用 spring boot 和带有代理的 JavaMailSender 发送邮件

xml - Spring批处理xmlns模式错误

java - 如何从 .xml 配置文件 (JSF) 引用 Java .properties 文件?