'How to read config file (*.yaml *.properties) without spring framework
I have a project but not in spring, how can I use annotation to read content in config files like *.yaml or *.properties
under resource package.
Solution 1:[1]
You can use SnakeYAML without Spring.
Download the dependency:
compile group: 'org.yaml', name: 'snakeyaml', version: '1.24'
Then you can load the .yaml (or .yml) file this way:
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 ); });
Edit: Upon further investigation, OP wants to know how to load properties in Spring boot. Spring boot has a build in feature to read properties.
Let's say you have a application.properties sitting in src/main/resources, and in it there is an entry say application.name="My Spring Boot Application"
, then in one of your classes annotated with @Component
or any of its sub-stereotype annotations, one can fetch values like this:
@Value("${application.name}")
private String applicationName;
The property in application.property file is now bound to this variable applicationName
You could also have a application.yml file and have the same property written this way
application:
name: "My Spring Boot Application"
You will get this property value the same way like last time by annotation a filed with @Value
annotation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Marcin Wasiluk |