Springboot中讀取.yml文件
阿新 • • 發佈:2018-10-26
方法 odin cte pat ref username -name 不能 -c
自定義配置文件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文件