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.
Read YAML File as Map in Java The Yaml instance introduces us to methods, such as load() which allow us to read and parse any InputStream , Reader or String with valid YAML data: InputStream inputStream = new FileInputStream(new File("student. yml")); Yaml yaml = new Yaml(); Map<String, Object> data = yaml.
To override your Spring Boot application properties when it's running on Kubernetes, just set environment variables on the container. To set an environment variable on a container, first, initialise a ConfigMap containing the environment variables that you want to override.
If you want to have multiple profiles in your Spring Boot project, by using the YAML file you just need to define one configuration file and put configuration data of specific profile into it, but if you use properties file you need to define individual file for each profile.
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 ); });
Reference.
Edit: Upon further investigation, OP wants to know how to load properties in Spring boot. Spring boot has a built-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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With