每日筆記---使用@ConfigurationProperties讀取yml配置


每日筆記---使用@ConfigurationProperties讀取yml配置

參考地址  https://www.cnblogs.com/mycs-home/p/8352140.html

1.添加pom依賴

1
2
3
4
5
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-configuration-processor</artifactId>
     <optional> true </optional>
</dependency>

 2.application.yml文件中添加需要配置的屬性,注意縮進

1
2
3
4
5
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,否則配置中的屬性值無法自動注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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類中執行自動注入,獲取屬性

1
2
3
4
5
//自動注入   
@Autowired
private  User user;<br>
//方法體內獲取屬性值
String url=user.getUrl();<br>System.out.print(url);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM