在 Web 开发的过程中,经常需要⾃定义⼀些配置⽂件
在springboot中存在两种配置文件,一种是以.properties结尾的配置文件,另一种是以.yml为结尾的配置文件。
在 application.properties 中配置:
xsj.title = 配置文件
xsj.description = 热爱生活,热爱编程
Spring Boot 也⽀持 Yaml 语法书写,⽐如上⾯的配置内容可以写到 application.yml ⽂件中
xsj:
title: 配置文件
description: 热爱生活,热爱编程
注:同时存在 application.yml 和 application.properties,并且⾥⾯配置相同, application.properties 的配置会覆盖 application.yml
在选择两种语法时, Yaml 语法更加简洁, properties 使⽤更加⼴泛,团队中保持⼀致即可。内容配置完成后,需要⾃定义⼀个对象来接收配置内容
读取单个配置文件
当需要从配置⽂件加载单个配置内容时,只需要使⽤ @Value 属性即可,在controller层建立helloController.java文件。
@Value("${xsj.title}")
private String title;
@RequestMapping("/helloValue")
public String value(){
return "使用value方式加载:"+title;
}
@Value("${xsj.title}") 会默认读取 application.properties 或者 application.yml ⽂件中的 xsj.title 配置属性值,并赋值给 title
在浏览器中输入http://localhost:8080/helloValue,返回结果 使用value方式加载:配置文件
读取多个配置
通常在项⽬中使⽤配置⽂件时,往往需要加载多个配置项,⽐如数据库连接参数等,通常会定义⼀个对象来接收多个配置项,⽅便在项⽬中使⽤。⽐如定义⼀个 xsjProperties 对象,来接收所有以 xsj开头的配置内容。
在model层创建xsjProperty.java
@Component
@ConfigurationProperties(prefix = "xsj")
public class xsjProperty {
private String title;
private String description;
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
}
@Component 的定义为实例,⽅便在 Spring Boot 项⽬中引⽤;
@ConfigurationProperties(prefix=“xsj”),表示以 xsj开头的属性会⾃动赋值到对象的属性中,⽐如,xsj.title 会⾃动赋值到对象属性 title 中
在controller层访问配置文件
@RestController
public class helloController {
@Resource
private xsjProperty xsjProperty;
@Value("${xsj.title}")
private String title;
@RequestMapping("/hello")
public String hello(){
return "使用component方式"+xsjProperty.getTitle();
}
@RequestMapping("/helloValue")
public String value(){
return "使用value方式加载:"+title;
}
}
@Resource用于记在配置的资源,把配置文件的内容注入到定义的对象中,之后使用get方法便可以调用配置文件的内容
自定义配置文件
有时候需要⾃定义配置⽂件,以便和系统使⽤的 application.properties ⽂件区分开,避免混淆。 Spring Boot对这种情况也有很好的⽀持。
在 resources ⽬录下创建⼀个 other.properties ⽂件,内容如下
other.title = 自定义配置文件
other.description = 自定义配置内容
和上⾯⼀样定义⼀个对象来接收配置⽂件的内容:
@Component
@ConfigurationProperties(prefix="other")
@PropertySource("classpath:other.properties")
public class OtherProperties {
private String title;
private String blog;
//省略getter settet⽅法
}
对⽐上⾯读取多个配置示例,多了⼀个注解来指明配置⽂件地址:
@PropertySource(“classpath:other.properties”),这个是用来定位自定义配置文件的位置
同样在helloController文件中添加映射
@RestController
public class helloController {
@Resource
private xsjProperty xsjProperty;
@Resource
private otherProperty otherProperty;
@Value("${xsj.title}")
private String title;
@RequestMapping("/hello")
public String hello(){
return "使用component方式"+xsjProperty.getTitle();
}
@RequestMapping("/helloValue")
public String value(){
return "使用value方式加载:"+title;
}
@RequestMapping("helloOther")
public String other(){
return "使用自定义配置加载多个配置======="
+otherProperty.getTitle();
}
}
不要忘记使用@Resource加载配置文件