首页 > 技术文章 > SpringBoot | 读取配置文件信息

jj81 2018-09-17 14:56 原文

server.port=8081  #修改端口号  
server.servlet.context-path= /SpringBoot #修改URL
#自定义配置
tz.name = xiaoming
tz.phone = 136****78789
tz.age = 18

  

 1 import org.springframework.beans.factory.annotation.Value;
 2 import org.springframework.context.annotation.PropertySource;
 3 import org.springframework.stereotype.Component;
 4 
 5 @Component
 6 @PropertySource("classpath:application.properties")  //Spring boot1.5.1之后,就废除了location参数,转而使用@PropertySource指定配置文件路径,不使用@ConfigurationProperties
 7 public class TzInformation {
 8     @Value("${tz.name}")
 9     private String name;
10     @Value("${tz.phone}")
11     private  String phone;
12     @Value("${tz.age}")
13     private String age;
14 
15     public String getName() {
16         return name;
17     }
18 
19     public String getPhone() {
20         return phone;
21     }
22 
23     public String getAge() {
24         return age;
25     }
26 
27     @Override
28     public String toString() {
29         return "TzInformation{" +
30                 "name='" + name + '\'' +
31                 ", phone='" + phone + '\'' +
32                 ", age='" + age + '\'' +
33                 '}';
34     }
35 }

 

 1 import org.springframework.beans.factory.annotation.Autowired;
 2 import org.springframework.web.bind.annotation.RequestMapping;
 3 import org.springframework.web.bind.annotation.RequestMethod;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 @RestController
 7 public class helloController {
 8     @Autowired
 9     TzInformation tzInformation;
10     @RequestMapping(value = "/hello",method = RequestMethod.GET)
11     public String say() {
12         return "Hello SpringBoot!   ";
13     }
14     
15     @RequestMapping(value = "/tz",method = RequestMethod.GET)
16     public String information(){
17         return tzInformation.toString();
18     }
19 }

 

推荐阅读