Inject Properties From YAML in Spring
In Spring, we can easily define configuration value in a YAML file, and inject those configuration into a Java class.
Take the following the YAML configuration file as an example.
YAML
server: localhost
# by default, spring split the string with comma
listValues: a,b,c,d
# if we want to split the string with customize character, we can use Spring EL
listValuesWithSpEL: a,b;c,d;e,f
# we can inject the whole complexObject into another class, with annotation ConfigurationProperties
complexObject:
port: 90
ssl: false
listValues: a,b,c,d
listValuesWithSpEL: a,b;c,d;e,f
We can create a Java bean class to inject those configurations.
Java
@Configuration
public class PropertyConfig {
@Value("${server}")
private String server;
@Value("${listValues}")
private String[] listValues;
@Value("#{'${listValuesWithSpEL}'.split(';')}")
private String[] listValuesWithSpEL;
// if it not set, it will use default value 'false'
@Value("${enabled:false}")
private boolean enabled;
}
@Configuration
@ConfigurationProperties(prefix = "complexObject")
public class ComplexObject {
@Value("${port}")
private int port;
@Value("${ssl}")
private boolean ssl;
@Value("#{'${listValuesWithSpEL}'.split(';')}")
private String[] listValuesWithSpEL;
@Value("${complexObject}")
private ComplexObject complexObject;
}