spring boot項目獲取application配置文件參數的兩種方式


前言:了解過spring boot這個技術的,應該知道spring boot的核心配置文件application.properties,當然也可以通過注解自定義配置文件**.properties的信息。

 

(1)核心配置文件application.properties內容如下:

  1. test.msg=Hello World SpringBoot  

 

方式一:使用@Value方式(常用)

1.   package Solin.controller;  

2.     

3.   import org.springframework.beans.factory.annotation.Value;  

4.   import org.springframework.web.bind.annotation.RequestMapping;  

5.   import org.springframework.web.bind.annotation.RestController;  

6.     

7.   @RestController  

8.   public class WebController {  

9.       @Value("${test.msg}")  

10.     private String msg;  

11.       

12.     @RequestMapping("/index1")   

13.     public String index1(){  

14.         return "方式一:"+msg;  

15.     }  

16. }

 

方式二:使用Environment方式

 

  1. package Solin.controller;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.beans.factory.annotation.Value;  
  5. import org.springframework.core.env.Environment;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RestController;  
  8.   
  9. @RestController  
  10. public class WebController {  
  11.     @Autowired  
  12.     private Environment env;  
  13.       
  14.     @RequestMapping("/index2")   
  15.     public String index2(){  
  16.         return "方式二:"+env.getProperty("test.msg");  
  17.     }  

 

 注意,使用類都必須已經加入到spring容器中,前面文章已經講解放入spring容器的方式


免責聲明!

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



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