Springboot(二)-application.yml默认的配置项以及读取自定义配置

2023-06-25,,

写在前面

=====

spring-boot 版本:2.0.0.RELEASE

=====

读取自定义配置

1.配置文件:sys.properties

supply.place=云南
supply.code=002

2.配置类:SupplyConfig.java

package com.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component; @Component
@PropertySource(value = "classpath:/sys.properties")
@ConfigurationProperties(prefix = "supply")
public class SupplyConfig { private String place ;
private String code; public String getPlace() {
return place;
} public void setPlace(String place) {
this.place = place;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code;
}
}

因为spring-boot使用了2.0.x,所以@ConfigurationProperties 没有locations的属性,改为使用@PropertySource注解代替配置文件路径

3.测试接口

@RestController
@RequestMapping("/test")
public class HelloWorldController{
@Autowired
SupplyConfig supplyConfig; @RequestMapping("supply/code")
public String getSupplyCode() {
return supplyConfig.getCode();
}
@RequestMapping("supply/name")
public String getSupplyName() {
return supplyConfig.getPlace();
}
}

问题1:中间出现读取中文配置出现乱码问题,在主文件application.yml 进行编码配置可以解决

server:
tomcat:
uri-encoding: UTF-8
spring:
http:
encoding:
charset: UTF-8
enabled: true
force: true
messages:
encoding: UTF-8

问题2:配置文件使用.yml格式的暂时还遇到问题,读取不到配置

Springboot(二)-application.yml默认的配置项以及读取自定义配置的相关教程结束。

《Springboot(二)-application.yml默认的配置项以及读取自定义配置.doc》

下载本文的Word格式文档,以方便收藏与打印。