1、配置文件中添加配置项application.yml
route-configuration:
properties:
#转成对象
router:
id: 1001
orgId: 32001
orgName: 南京
url: http://localhost:9527
userId: 123456
userName: 123
centerCode: 32001
#转成list<对象>
routerList:
- id: 1001
orgId: 32001
orgName: 南京
url: http://localhost:9527
userId: 123456
userName: 123
centerCode: 32001
#转成map<String,对象>
routerMap:
32001:
id: 1001
orgId: 32001
orgName: 南京
url: http://localhost:9527
userId: 123456
userName: 123
centerCode: 32001
list:
- {key: 'value',key1: 'value1'}
2.创建config加载配置项内容到对象中
@Data @Component // @PropertySource("classpath:roteConfig.yml") 读取指定路径配置文件 @ConfigurationProperties(prefix = "route-configuration.properties") public class TestConfig { private Router router; private List<Router> routerList; private Map<String, Router> routerMap; private List<Map<String, string>> list; }
3。启动服务,获取对象值
引用地方注入对象
@Autowired private TestConfig testConfig;
// 加载的配置配置项 Router router = testConfig.getRouter(); List<Router> routerList = testConfig.getRouterList(); Map<String, Router> routerMap = testConfig.getRouterMap();
就可以获取对应的配置值
2.自定义的配置文件读取,如从test.properties读取
Resource resource= new ClassPathResource("test.properties");
EncodeResource encodeResource = new EncodeResource(resource,"UTF-8");
Properties prop = ProperiesLoadUtils.loadProperties(encodeResource);
prop.getProperty("pro");//即可获取指定的值