一,介绍
在spring boot中,配置文件是用来设置应用程序的各种参数和操作模式的重要部分。spring boot支持两种主要类型的配置文件:properties文件和yaml 文件。这两种文件都可以用来定义相同的配置,但它们在格式和表达能力上有所不同。
二,properties 配置方式
properties文件是java平台最传统的配置方式,文件扩展名为 .properties。这种格式非常简单,主要由键值对组成,每一对键值对设置一个配置属性。
示例:
定义模型person类:
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.stereotype.component;
@component
@configurationproperties(prefix="person")
public class person {
private string name;
private int age;
private string uuid;
private dog dog;
// standard getters and setters
public static class dog {
private string name;
private string breed;
// standard getters and setters
}
}properties 配置
person.name=john doe
person.age=35
person.uuid=${random.uuid}
person.dog.name=rex
person.dog.breed=labrador这样配置后,spring boot 会自动application.properties中的相关配置注入到 person对象和其内部的 dog对象。
使用 @value注解也可以直接在 spring boot 应用中注入配置值,例
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;
@component
public class person {
@value("${person.name}")
private string name;
@value("${person.age}")
private int age;
@value("${person.uuid}")
private string uuid;
// 内部类和其他配置略
}三,yaml 配置方式
yaml 是一种层次结构化的数据格式,相比于 properties文件,它支持列表和嵌套的对象,使得配置更加清晰和组织化。
yaml配置:
person:
name: "john doe"
age: 35
uuid: ${random.uuid}
dog:
name: "rex"
breed: "labrador"这时要将yaml文件中的配置自动映射到一个java类中,需要在spring boot应用中定义相应的配置类,并使用@configurationproperties注解。
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.context.annotation.configuration;
import org.springframework.context.annotation.propertysource;
import org.springframework.stereotype.component;
@configuration
@configurationproperties(prefix = "person")
public class person {
private string name;
private int age;
private string uuid;
private dog dog;
@component
public static class dog {
private string name;
private string breed;
// getters and setters
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public string getbreed() {
return breed;
}
public void setbreed(string breed) {
this.breed = breed;
}
}
}四,对比
1. 可读性
- yaml 由于其支持层级结构,通常在表达更复杂的配置时更加清晰和易读。
- properties 文件更适合简单的平面键值对,但在需要表达嵌套配置时可读性较差。
2. 表达能力
- yaml 支持复杂的数据结构,如列表和字典(即嵌套的对象),这使得它在表达如安全规则、路由配置等复杂配置时非常有用。
- properties 文件不支持直接的层级或复杂结构,所有结构都必须通过点分隔的方式平铺开来表达。
3. 错误检测
- yaml 文件由于格式更加复杂,对缩进非常敏感,错误的缩进可能导致整个文件无法解析。
- properties 文件结构简单,缩进和格式错误的容忍度较高。
4. 使用场景
- 如果配置较为简单,或是迁移遗留项目而不希望引入新的复杂性,那么使用
.properties可能更合适。 - 对于新项目或需要表达复杂配置的情况,
.yaml提供了更强的表达能力和更好的可读性。
以上就是springboot实现给属性赋值的两种方式的详细内容,更多关于springboot给属性赋值的资料请关注代码网其它相关文章!
发表评论