【问题标题】:Call custom constructor when binding a map绑定地图时调用自定义构造函数
【发布时间】:2011-01-05 13:32:51
【问题描述】:

绑定列表时,我可以通过在 AutoPopulatingList 中使用自定义 ElementFactory 以这种方式控制对象的实例化方式(用于实例调用具有多个参数的构造函数):

public class Foo{

    private List<NestedFoo> nested = new AutoPopulatingList<NestedFoo>(new ElementFactory<NestedFoo>() {
        @Override
        public NestedFoo createElement(int index) throws ElementInstantiationException {
            return new NestedFoo(index);
        }       
    });
}

当集合是 Map 而不是 List 时,有什么方法可以做类似的事情吗?我的意思是当表单发送类似 nested['fooParam'] 的内容时,我想在地图“自动增长”时使用 fooParam 调用构造函数。

谢谢。

【问题讨论】:

    标签: java spring data-binding collections spring-mvc


    【解决方案1】:

    不知道 Spring 中的任何解决方案,但 GuavaMapMaker 类可以让您创建计算图:

    ConcurrentMap<Key, Graph> graphs = new MapMaker()
       .concurrencyLevel(4)
       .softKeys()
       .weakValues()
       .maximumSize(10000)
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .makeComputingMap(
           new Function<Key, Graph>() {
             public Graph apply(Key key) {
               // this is where your values are created on demand
               return createExpensiveGraph(key);
             }
           });
    

    参考:


    顺便说一句,Apache Commons / Collections 也有类似的功能:

    MapUtils.lazyMap(Map, Transformer)

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 1970-01-01
      • 2012-05-22
      • 2011-02-22
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      相关资源
      最近更新 更多