春ELリスト、マップの例

Spring ELリスト、マップの例

この記事では、Spring ELを使用してMapListから値を取得する方法を示します。 実際、SpELの方法はMapとListで機能し、Javaでもまったく同じです。 例を参照してください:

        //get map whete key = 'MapA'
    @Value("#{testBean.map['MapA']}")
    private String mapA;

    //get first value from list, list is 0-based.
    @Value("#{testBean.list[0]}")
    private String list;

注釈のSpring EL

ここでは、HashMapArrayListを作成し、テスト用の初期データをいくつか作成しました。

package com.example.core;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("customerBean")
public class Customer {

    @Value("#{testBean.map['MapA']}")
    private String mapA;

    @Value("#{testBean.list[0]}")
    private String list;

    public String getMapA() {
        return mapA;
    }

    public void setMapA(String mapA) {
        this.mapA = mapA;
    }

    public String getList() {
        return list;
    }

    public void setList(String list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "Customer [mapA=" + mapA + ", list=" + list + "]";
    }

}
package com.example.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

@Component("testBean")
public class Test {

    private Map map;
    private List list;

    public Test() {
        map = new HashMap();
        map.put("MapA", "This is A");
        map.put("MapB", "This is B");
        map.put("MapC", "This is C");

        list = new ArrayList();
        list.add("List0");
        list.add("List1");
        list.add("List2");

    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

}

それを実行します

       Customer obj = (Customer) context.getBean("customerBean");
       System.out.println(obj);

出力

Customer [mapA=This is A, list=List0]

XMLのSpring EL

Bean定義XMLファイルで同等のバージョンを参照してください。



    
        
        
    

    

ソースコードをダウンロード

ダウンロード–Spring3-EL-Map-List-Example.zip(6 KB)