Spring Boot使用YAML(YAML Ain’t Markup Language)作为配置文件的格式,通过spring-boot-starter模块内置的spring-boot-configuration-processor模块来解析YAML文件。
在Spring Boot应用中,可以通过@ConfigurationProperties注解将YAML文件中的配置映射到Java对象中。例如:
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component@ConfigurationProperties(prefix = "myapp")public class MyAppProperties { private String name; private int port; // getters and setters}在application.yml中配置:
myapp: name: MyApp port: 8080然后在Spring组件中注入MyAppProperties对象即可获取配置值。
另外,Spring Boot还提供了@Value注解来从YAML文件中获取单个配置值。例如:
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class MyComponent { @Value("${myapp.name}") private String appName; @Value("${myapp.port}") private int appPort; // getters and setters}这样就可以通过@Value注解直接获取YAML文件中的配置值。


