1.添加pom依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
2.application.yml文件中添加需要配置的屬性,注意縮進
Myyml: username: cs password: 123456 url: jdbc:mysql://localhost:3306/test driver: com.mysql.jdbc.Driver
3.新建一個類,@Component注解表明是組件,可被自動發現,@ConfigurationProperties注解之前是location屬性表明配置文件位置,prefix表示讀取的配置信息的前綴,但新版本中廢除了location屬性(網上說是1.5.2之后),故只寫前綴,默認讀取application.yml中數據。重點!!一定要在這個類中寫getter和setter,否則配置中的屬性值無法自動注入
package com.cs.background.util; import lombok.ToString; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "Myyml") public class User{ //數據庫連接相關 private String url; private String driver; private String username; private String password; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
4.Controller類中執行自動注入,獲取屬性
//自動注入 @Autowired private User user;
//方法體內獲取屬性值 String url=user.getUrl();
System.out.print(url);
5.啟動springboot入口類,調用對應controller對應的方法,控制台打印獲取的值。