SpringBoot有三大特点,自动配置,起步依赖,Actuator对运行状态的监控。
1.将配置文件的值注入到变量中
先说两个注解@SpringBootApplication,它包含了配置,自动配置,包扫描这个三个注解的功能,@RestController是@Controller和@ResponseBody的组合注解
首先配置好配置文件:
my:
name: Mr.Wang
age : 25
然后注入属性:
@RestController
public class TestController {
@Value("${my.name}")
private String name;
@Value("${my.age}")
private int age;
@RequestMapping("/my")
public String my() {
return name + ":" + age;
}
}
结果:
2.将配置文件的值赋值给实体类
修改配置文件:
my:
name: Mr.Wang
age : 25
uuid : ${random.uuid}
max : ${random.int(10)}
value : ${random.value}
新建配置类:
加上注解@ConfigurationProperties表示这个是配置属性类,加上prefix = "my"才知道读哪些配置,配置@Component在SpringBoot启动的时候,才能通过包扫描将该类作为一个Bean加入IOC容器中。
@ConfigurationProperties(prefix = "my")
@Component
public class User {
private String name;
private int age;
private String uuid;
private int max;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
修改类:
@Autowired
private User user;
@RequestMapping("/wang")
public String wang(){
return user.getName()+user.getUuid()+user.getValue()+user.getAge()+user.getMax();
}
测试:
如果说这个配置文件不是application.yml,该如何指定去读取配置呢?
比如说现在有一个配置文件:
新建一个配置类:注解和默认配置文件i相比是有变化的,@PropertySourceh指明了路径。
@ConfigurationProperties(prefix = "com.wx")
@Configuration
@PropertySource(value = "classpath:test.properties")
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
使用起来也有变化,好像不用指明是哪个配置类也能用
@RestController
@EnableConfigurationProperties({User.class})
public class TestController {
@Autowired
private User user;
@RequestMapping("/user")
public String wang(){
return user.getName()+user.getAge();
}
}
测试:
3.多环境配置文件
比如来两个环境,测试环境和开发环境,假设在测试环境下我要使用8082端口,开发环境我要使用8083端口怎么弄?
两个配置文件端口这样配置:
配置启动时读那个文件:
启动之后端口就是8082:
命令启动:
4.运行状态的监控
Spring Boot Actuator 的关键特性是在应用程序里提供众多的web节点,通过这些节点可以实时的了解应用程序的运行状况,
management:
server:
port: 9001
endpoints:
web:
base-path: /actuator
exposure:
include: '*'
endpoint:
health:
show-details: always
shutdown:
enabled: true
配置文件的含义:
#actuator端口
management.server.port=9001
#修改访问路径 2.0之前默认是/ 2.0默认是 /actuator 可以通过这个属性值修改
management.endpoints.web.base-path=/monitor
#开放所有页面节点 默认只开启了health、info两个节点
management.endpoints.web.exposure.include=*
#显示健康具体信息 默认不会显示详细信息
management.endpoint.health.show-details=always
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
测试:
查看应用程序运行的健康状态和磁盘状态
查看运行程序的bean: