This page is mainly for your own memory.
If you write it very roughly, it will be in the following order.
For example, if you have the following application.yml
ymlSetting:
stringKey: "Some kind of string"
mapA:
key1: "value1"
key2: "value2"
Create a class to read and store values from application.yml. Set the application.yml key to the prefix of the "@ConfigurationProperties" annotation. Then, you can define that this class will read this definition. (In the example, the Setting class defines that the setting value under ymlSetting is read.)
Each defined item is stored as a member variable. The non-nested item (stringKey) is of type String Items with child elements (mapA) can be declared as Maps.
When referencing the value in the property file, the value will be referenced using the Getter of the declared member variable.
Settings.java
package jp.co.sample;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "ymlSetting")
public class Settings {
private String stringKey;
private Map<String, String> mapA;
public void setStringKey(String stringKey){
this.stringKey = stringKey;
}
public String getStringKey(){
return stringKey;
}
public void setMapA(Map<String, String> mapA){
this.mapA = mapA;
}
public Map<String, String> getMapA(){
return mapA;
}
}
For example, when the property value is output as standard, it looks like this.
SpringBootConfigApplication.java
package jp.co.sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootConfigApplication implements CommandLineRunner{
@Autowired
private Setting setting; //Property file reading class
public static void main(String[] args) {
SpringApplication.run(SpringBootConfigApplication.class, args);
}
@Override
public void run(String... args) {
System.out.println("string = " + Settings.getStringKey());
System.out.println("key1 = " + Settings.getMapA().get("key1"));
System.out.println("key2 = " + Settings.getMapA().get("key2"));
}
}
Recommended Posts