我有一个项目,但不是spring的,如何使用注解读取资源包下的*.yaml或*.properties
等配置文件内容。
最佳答案
您可以在没有 Spring 的情况下使用 SnakeYAML。
下载依赖项:
compile group: 'org.yaml', name: 'snakeyaml', version: '1.24'
然后您可以通过以下方式加载 .yaml(或 .yml)文件:
Yaml yaml = new Yaml();
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("youryamlfile.yaml"); //This assumes that youryamlfile.yaml is on the classpath
Map<String, Object> obj = yaml.load(inputStream);
obj.forEach((key,value) -> { System.out.println("key: " + key + " value: " + value ); });
编辑:经过进一步调查,OP想知道如何在Spring boot中加载属性。 Spring Boot 有一个内置的读取属性的功能。
假设您在 src/main/resources 中有一个 application.properties,其中有一个条目 application.name="My Spring Boot Application"
,然后在您的其中一个使用 @Component
或其任何子构造型注释注释的类,可以获取如下值:
@Value("${application.name}")
private String applicationName;
application.property 文件中的属性现在绑定(bind)到此变量 applicationName
您还可以有一个 application.yml 文件并以这种方式编写相同的属性
application:
name: "My Spring Boot Application"
您将像上次一样通过使用 @Value
注释的注释来获取此属性值。
关于java - 如何在没有spring框架的情况下读取配置文件(*.yaml *.properties),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57246626/