- A+
所属分类:Java
# yml文件 spring: #list<map> testList: - name: 小王 age: 12 - name: 小李 age: 13 # map<String,String> testMap: name: 小朱 age: 14 testname: 小明
获取配置文件有两种方式
使用 @Value
package com.example.demo; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Map; @Data //@Service @Component public class TestConfig { //注释的两行会报错,java.lang.IllegalStateException: Failed to load ApplicationContext // @Value("${spring.testMap}") // private Map<String,String> testMap; @Value("${testname}") private String name; @Value("${spring.testMap.name}") private String name2; private String name1; }
使用@ConfigurationProperties
package com.example.demo;
import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; @Data @Component @ConfigurationProperties(prefix = "spring") public class TestConfigurationProperties { private List<Map> testList; private Map<String,String> testMap; @Value("${testname}") private String name; } test: @Autowired private TestConfig testConfig; @Test public void test7(){ System.out.println(testConfig.getName());//小明 System.out.println(testConfig.getName2());//小朱 } @Autowired private TestConfigurationProperties testConfigurationProperties; @Test public void test8(){ System.out.println(testConfigurationProperties.getTestMap()); System.out.println(testConfigurationProperties.getTestList()); System.out.println(testConfigurationProperties.getName()); } /** {name=小朱, age=14} [{name=小王, age=12}, {name=小李, age=13}] 小明 */