(一)项目属性配置之属性配置文件
以前的Spring配置文件都是“*.properties
”,而在SpringBoot中支持一种更优化的配置文件“*.yml
”,它的用法如下:
#server中的参数都是SpringBoot提供的
server:
#设置项目端口号
port: 8081
servlet:
#设置项目的根路径
context-path: /springboot
(二)将属性文件读取到类中
将属性文件读取到类中,有两种情况:
第一种:单属性,比如
#自定义参数(配合@value注解读取)
cupSize: D
对于这种,我们只要配合“@value(“{cupSize}”)”注解,即可将属性读出来(和Spring相同)。
第二种:多属性。对于这种我们就需要利用“@ConfigurationProperties”注解将属性读到JavaBean中,然后再通过JavaBean来读取对应的值。不过在用“@ConfigurationProperties”注解之前,需要现在pom文件中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
多属性读取如下:
girl:
cupSize: C
height: 160
weight: 90
` JavaBean:
@Component
//前缀对应配置文件中自定义属性的根(girl)
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private String cupSize;
private String height;
private String weight;
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
` 使用:
@RestController
public class GirlController {
@Autowired
private GirlProperties girlProperties;
@RequestMapping
public String welcomeToGirl(){
return "小姐姐的罩杯:" + girlProperties.getCupSize();
}
}
(三)读取自定义属性文件
Springboot默认读取resource文件夹下的application.*配置文件,而在实际的项目中,我们一般是将所有的配置文件放在一个统一的目录下,比如:
对于这些配置文件,我们需要配合“@PropertySource”注解来指定配置文件的位置,例如:
@Component
@ConfigurationProperties(prefix = "girl")
@PropertySource(value = {"classpath:config/application.yml"})
public class GirlProperties {
private String cupSize;
private String height;
private String weight;
......
}
上面的代码就是读取“resource/config”文件夹下的自定义配置文件“application.yml”
(四)常见错误及其解决办法
1.Spring Boot Annotion processor not found in classpath
解决办法:需要在pom中添加dependences
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.Re-run Spring Boot Configuration Annotation Processor to update generated metadata
该提示,不影响代码执行。只是提醒用户,进行必要的重新编译。再当文件进行了有效的更新时,该提示也会消失。