springboot如何解析yml文件
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;
@Component
public class MyComponent {
@Value("${myapp.name}")
private String appName;
@Value("${myapp.port}")
private int appPort;
// getters and setters
}
这样就能够通过@Value注解直接获得YAML文件中的配置值。
TOP