@Value 注入Map list等類型

在application.properties寫入下面代碼

test.boolean=true
test.string=abc
test.integer=123
test.long=123
test.float=1.2345678123456
test.double=1.2345678123456
test.array=1,3,4,5,6,1,2,3
test.list=1,3,4,5,6,1,2,3
test.set=1,3,4,5,6,1,2,3
test.map={name:"張三", age:18}

 

使用junit進行測試

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ApplicationBootstrap.class})
public class DemoTest {

    @Value("${test.boolean}")
    private Boolean testBoolean;

    @Value("${test.string}")
    private String testString;

    @Value("${test.integer}")
    private Integer testInteger;

    @Value("${test.long}")
    private Long testLong;

    @Value("${test.float}")
    private Float testFloat;

    @Value("${test.double}")
    private Double testDouble;

    @Value("#{'${test.array}'.split(',')}")
    private String[] testArray;

    @Value("#{'${test.list}'.split(',')}")
    private List<String> testList;

    @Value("#{'${test.set}'.split(',')}")
    private Set<String> testSet;


    @Value("#{${test.map}}")
    private Map<String, Object> testMap;

    @Test
    public void demoTest(){
        System.out.println(testBoolean); // true
        System.out.println(testString); // abc
        System.out.println(testInteger); // 123
        System.out.println(testLong); // 123
        System.out.println(testFloat); // 1.2345678
        System.out.println(testDouble); // 1.2345678123456

        System.out.println(JSON.toJSONString(testArray)); 
        // ["1","3","4","5","6","1","2","3"]

        System.out.println(testList.toString()); 
        // [1, 3, 4, 5, 6, 1, 2, 3]

        System.out.println(testSet.toString()); 
        // [1, 3, 4, 5, 6, 2]

        System.out.println(testMap.toString()); 
        // {name=張三, age=18}
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章