您的位置:宽带测速网 > 编程知识 > springboot如何获取yml的值

springboot如何获取yml的值

2025-06-21 20:40来源:互联网 [ ]

在Spring Boot中,可以通过在配置文件(如application.yml)中定义属性值,然后在Java代码中使用@Value注解来获取这些属性的值。例如:

在application.yml中定义属性:

app:name: My Applicationversion: 1.0

在Java类中使用@Value注解获取属性值:

import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class AppConfig {@Value("${app.name}")private String appName;@Value("${app.version}")private String appVersion;public String getAppName() {return appName;}public String getAppVersion() {return appVersion;}}

然后在其他类中可以通过@Autowired注解注入AppConfig类,并调用getAppName()和getAppVersion()方法来获取配置文件中定义的属性值。例如:

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class MyService {@Autowiredprivate AppConfig appConfig;public void printAppInfo() {System.out.println("App name: " + appConfig.getAppName());System.out.println("App version: " + appConfig.getAppVersion());}}

这样就可以在Spring Boot中通过@Value注解来获取配置文件(如application.yml)中定义的属性值。