SpringBoot配置文件使用

最近很烦,公司的事情很多,连着好几个星期的下雨天,没见过太阳

一:配置文件

application.properties

1
2
3
4
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?useSSL=false
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

获取的方法一

1
2
3
4
5
6
7
8
9
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
ConfigurableApplicationContext app = SpringApplication.run(DemoApplication.class, args);
// application.properties文件中的name=chenyanwu
System.out.println(app.getEnvironment().getProperty("name"));
}
}

获取的方法二

1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
public class HelloWorldController {

@Value("${name}")
private String name;
@Value("${age}")
private int age;

@RequestMapping("/getUser")
public String getUser() {
return "name: " + name + ";age:" + age;
}
}

获取的方法三

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
@Component
@ConfigurationProperties(prefix="user")
public class Person {
@Value("${name}")
private String name;

@Value("${age}")
private Integer age;
private String addr;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getAddr() {
return addr;
}

public void setAddr(String addr) {
this.addr = addr;
}

@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", addr=" + addr + "]";
}
}

实现代码

1
2
3
4
5
6
7
@Autowired
private Person person;

@RequestMapping("/getPerson")
public String getPerson() {
return person.toString();
}

参考:https://mp.weixin.qq.com/s/12x_1-NSV5ZLgvHIxLRbkQ