'handle environment variable in .yml with jackson-dataformat-yaml

I'm using jackson to retrive file .yml into pojo java. It's working fine.

how could I handle environment variables in .yml when read to pojo? jackson has this implementation? example:

attr1: ${ENV_ATTR} # read this value from environment when has ${}

Dependencie

implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.13.1'

Implementation code


var fileYml = new File(getClass().getClassLoader().getResource("file.yml").toURI());

var mapper = new ObjectMapper(new YAMLFactory());
    mapper.setPropertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE);
    
var entityFromYml = mapper.readValue(fileYmlContent, MyEntity.class);


note: I'm not using spring or spring boot.



Solution 1:[1]

There's Apache Commons' StringSubstitutor which does the job. You can either pre-process the input string with it, or post-process each loaded string.

Post-processing obviously works only on values that load into Strings so you can't use it e.g. on a value that loads into an int.

Pre-processing, on the other hand, is dangerous because it doesn't protect you against YAML special characters in the env variable's value. In your example, set ENV_ATTR to

foo
bar: baz

and after substitution, you will have

attr1: foo
bar: baz

which might not be desired.

If you want to guard against that but also want to substitute in non-String values, you'll need to use SnakeYAML's API directly and specialize its Composer. Jackson is an abstraction API on top of SnakeYAML that restricts what you can do, so this is not possible with Jackson.

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 flyx