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容器的方式

posted @ 2018-01-18 00:05  forzheng  阅读(31281)  评论(0编辑  收藏  举报