Spring Boot中配置文件application.properties使用


一、配置文檔配置項的調用


 

啟動后在瀏覽器直接輸入http://localhost:18080/user/test,就直接打印出配置文件中的配置內容。

 

二、綁定對象bean調用

有時候屬性太多了,一個個綁定到屬性字段上太累,官方提倡綁定一個對象的bean,這里我們建一個ConfigBean.java類,頂部需要使用注解@ConfigurationProperties(prefix = “com”)來指明使用哪個

 

1
2
3
4
5
6
7
@ConfigurationProperties(prefix = "com")
public class ConfigBean {
private String name;
private String id;

// 省略getter和setter
}

 

這里配置完還需要在spring Boot入口類加上@EnableConfigurationProperties並指明要加載哪個bean,如果不寫ConfigBean.class,在bean類那邊添加

 

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableConfigurationProperties({ConfigBean.class})
public class Chapter2Application {

public static void main(String[] args) {
SpringApplication.run(Chapter2Application.class, args);
}
}

 

最后在Controller中引入ConfigBean使用即可,如下:

 

1
2
3
4
5
6
7
8
9
10
@RestController
public class UserController {
@Autowired
ConfigBean configBean;

@RequestMapping("/")
public String hexo(){
return configBean.getName()+configBean.getId();
}
}

 

三、參數間引用

 

在application.properties中的各個參數之間也可以直接引用來使用,就像下面的設置:

 

1
2
3
com.name="張三"
com.id="8"
com.psrInfo=${com.name}編號為${com.id}

 

這樣我們就可以只是用psrInfo這個屬性就好

 

 四、使用自定義新建的配置文件

  我們新建一個bean類,如下:

1
2
3
4
5
6
7
8
@Configuration
@ConfigurationProperties(prefix = "com.md")
@PropertySource("classpath:test.properties")
public class ConfigTestBean {
private String name;
private String want;
// 省略getter和setter
}

主要就是加了一個注解:@PropertySource("classpath:test.properties")

 

五、配置文件優先級

 

application.properties和application.yml文件可以放在一下四個位置:

 

  • 外置,在相對於應用程序運行目錄的/congfig子目錄里。
  • 外置,在應用程序運行的目錄里
  • 內置,在config包內
  • 內置,在Classpath根目錄

 

同樣,這個列表按照優先級排序,也就是說,src/main/resources/config下application.properties覆蓋src/main/resources下application.properties中相同的屬性,如圖:

 

此外,如果你在相同優先級位置同時有application.properties和application.yml,那么application.yml里面的屬性就會覆蓋application.properties里的屬性。

 

詳細參考:http://tengj.top/2017/02/28/springboot2/

 


免責聲明!

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



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