开发者

Call custom constructor when binding a map

When a list is binded I can control how th开发者_运维百科e objects are instantiated (for instace invoke a constructor with several params) by using a custom ElementFactory in an AutoPopulatingList in this way:

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);
        }       
    });
}

Is there any way to do something similar when the collection is a Map instead of a List? I mean when the form sends something like nested['fooParam'] I want to call a constructor with the fooParam when the map is 'auto-grown'.

Thanks.


Don't know any solution in Spring, but Guava's MapMaker class lets you create a computing map:

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);
         }
       });

Reference:

  • MapMaker.makeComputingMap(Function<Key,Val>)

BTW, Apache Commons / Collections has a similar feature:

MapUtils.lazyMap(Map, Transformer)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜