Springboot中读取.yml文件
Posted MySql_3306
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot中读取.yml文件相关的知识,希望对你有一定的参考价值。
自定义配置文件application-dev.yml
1 spring: 2 dataresource: 3 druid: 4 driver-class-name: com.mysql.jdbc.Driver 5 url: jdbc:mysql://127.0.0.1:3306/appcloud?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC 6 username: root 7 password: root
创建一个实体类 configYml
1 @Component 2 @PropertySource("classpath:application-dev.yml")//制定读取配置文件的路径 3 @ConfigurationProperties(prefix = "spring.datasource.druid")//指定读取的前缀 4 public class ConfigYml { 5 6 @Value("${driver-class-name}")//配置文件中的命名为driver-class-name;java中不能命名不能有下划线。所以可以使用@Value注解获取值 7 private String driver; 8 private String url; 9 private String username; 10 private String password; 11 12 @Override 13 public String toString() { 14 return "ConfigYml{" + 15 "driver=‘" + driver + ‘‘‘ + 16 ", url=‘" + url + ‘‘‘ + 17 ", username=‘" + username + ‘‘‘ + 18 ", password=‘" + password + ‘‘‘ + 19 ‘}‘; 20 } 21 22 public String getDriver() { 23 return driver; 24 } 25 26 public void setDriver(String driver) { 27 this.driver = driver; 28 } 29 30 public String getUrl() { 31 return url; 32 } 33 34 public void setUrl(String url) { 35 this.url = url; 36 } 37 38 public String getUsername() { 39 return username; 40 } 41 42 public void setUsername(String username) { 43 this.username = username; 44 } 45 46 public String getPassword() { 47 return password; 48 } 49 50 public void setPassword(String password) { 51 this.password = password; 52 } 53 54 55 56 }
1 @Autowired 2 private ConfigYml configYml;
直接调用configYml的get方法即可
以上是关于Springboot中读取.yml文件的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot读取.yml/.properties配置文件