Reactive way of reading YAML with Jackson using Spring boot webflux

746 Views Asked by At

The yamlObjectMapper in configuration

@Bean
    public ObjectMapper yamlObjectMapper() {
        ObjectMapper yamlObjectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature
            .WRITE_DOC_START_MARKER));
        yamlObjectMapper.findAndRegisterModules();
        return yamlObjectMapper;
    }

The Service to parse yaml file

@Service
public class CustomerService {      

  @Autowired
  @Qualifier("yamlObjectMapper")
  private ObjectMapper yamlObjectMapper;

  public Customer get() {
    try {          
      InputStream inputStream = ResourceUtils.getURL("classpath:/files/test.yaml").openStream();
      return yamlObjectMapper.readValue(inputStream, Customer.class);
    } catch (IOException ex) {
      throw new IllegalStateException(ex);
    }
  }

  @Data
  public static class Customer {
    private String name;
    private String surname;
    private String email;
  }
}

I guess IO operations are blocking, how this can be done using reactive way?

1

There are 1 best solutions below

0
Vova Bilyachat On

I would rather use configuration binding since probably you need to read it once.

package com.vob.webflux.webfilter.controller;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = "classpath:config.yml", factory= YamlPropertySourceFactory.class)
@Getter
public class YamlFooProperties {
    @Value("${test}")
    private String test;
}

Factory

package com.vob.webflux.webfilter.controller;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
            throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());

        Properties properties = factory.getObject();

        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
    }
}

Source factory from