Skip to content

SpringBoot 配置文件

在 SpringBoot 开发钟,我们经常需要定义一些配置类,可以采用@Value()或者@ConfigurationProperties。

@Value 集成步骤

  1. 在 resources 目录下创建 application.properties
text
runtime.version=3.10
runtime.name=DL
  1. 创建对应的实体类对象
java
@Component
public class RuntimeProperties {

    @Value("${runtime.version}")
    private String version;

    @Value("${runtime.name}")
    private String name;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "RuntimeProperties{" +
                "version='" + version + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
  1. 编写测试类
java
@SpringBootTest
public class YmlApplicationTest {

    @Autowired
    private RuntimeProperties runtimeProperties;


    @Test
    public void test() {
        System.out.println( runtimeProperties.toString());
    }

}
  1. 运行
text
RuntimeProperties{version='3.10', name='DL'}

@ConfigurationProperties 集成步骤

  1. application.yml 定义相关参数
yml
python:
  version: "3.10"
  torch-version: "1.10"
  1. 定义实体类对象
java
@Component
@ConfigurationProperties(prefix = "python")
public class RuntimeYml {

    private String version;

    private String torchVersion;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getTorchVersion() {
        return torchVersion;
    }

    public void setTorchVersion(String torchVersion) {
        this.torchVersion = torchVersion;
    }

    @Override
    public String toString() {
        return "RuntimeYml{" +
                "version='" + version + '\'' +
                ", torchVersion='" + torchVersion + '\'' +
                '}';
    }
}
  1. 编写测试函数
java
 @Autowired
    private RuntimeYml runtimeYml;

    @Test
    public void test1() {
        System.out.println(runtimeYml.toString());
    }
  1. 运行
text
RuntimeYml{version='3.10', torchVersion='1.10'}

@ConfigurationProperties 与 @Value 对比

功能@ConfigurationProperties@Value
松散绑定
元数据支持
spEL 表达式

Released under the MIT License.