袁文涛*_*袁文涛 5 java annotations config
我有一个项目,但不是在 spring,如何使用注释读取*.yaml or *.properties资源包下的配置文件中的内容。
您可以在没有 Spring 的情况下使用 SnakeYAML。
下载依赖:
compile group: 'org.yaml', name: 'snakeyaml', version: '1.24'
Run Code Online (Sandbox Code Playgroud)
然后您可以通过以下方式加载 .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,valye) -> { System.our.println("key: " + key + " value: " + value ); });
Run Code Online (Sandbox Code Playgroud)
编辑:经过进一步调查,OP 想知道如何在 Spring Boot 中加载属性。Spring Boot 具有内置功能来读取属性。
假设您有一个 application.properties 位于 src/main/resources 中,其中有一个条目 say application.name="My Spring Boot Application",然后在您使用@Component或任何其子构造型注释注释的类中,可以获取如下值:
@Value("${application.name}")
private String applicationName;
Run Code Online (Sandbox Code Playgroud)
application.property 文件中的属性现在绑定到这个变量 applicationName
您也可以有一个 application.yml 文件并以这种方式编写相同的属性
application:
name: "My Spring Boot Application"
Run Code Online (Sandbox Code Playgroud)
您将通过注释 a 与@Valueannotation以与上次相同的方式获得此属性值。