Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
袁文涛 Avatar asked Jul 29 '19 02:07

袁文涛


People also ask

How do I read a YAML file in Java?

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.

How do I bypass Spring boot properties?

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.

Which is better to configure a Spring boot project properties or YAML?

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.


1 Answers

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.

like image 84
Faraz Avatar answered Oct 23 '22 22:10

Faraz