Home > OS >  How to get child properties from spring config
How to get child properties from spring config

Time:09-22

I have the following configuration:

external:
  shop-service:
    url: localhost:8080
    timeout: 5000
  pet-service:
    url: localhost:8081
    timeout: 10000
  user-service:
    url: localhost:8082
    timeout: 15000

I want to create some config library that will read these properties in every my service. In every service I can have different clients with different values of properties, but all of them have the same structure.

Any ways how I can get a map that will contain client name as a key and object that has url and timeout values, if I know only external property at the beginning and don't know exact client names?

CodePudding user response:

You can create a configuration class which maps your properties into a map.

@Getter
@Configuration
@ConfigurationProperties
public class Properties {
    
    private Map<String, String[]> external = new HashMap<>();
    
}

In my opinion, you should avoid using String array as value type. Instead of, you should create a POJO to map the url and timeout properties.

@Getter
@Configuration
@ConfigurationProperties
public class Properties {

    private Map<String, Data> external = new HashMap<>();

    @Getter
    @Setter
    @ToString
    public static class Data {
        private long timeout;
        private String url;
    }
    
}

Note: the Properties class must have a getter for the map, and the Data properties must have a getter and setter for each attribute.

CodePudding user response:

this is my solution

private static final String BASE_PROPERTY = "clients.";
private static final String DELIMITER = ".";

private final org.springframework.core.env.Environment environment;

public Set<String> getClientNames() {
    return Arrays
        .stream(((EnumerablePropertySource<?>) ((ConfigurableEnvironment) environment)
            .getPropertySources()
            .stream()
            .filter(OriginTrackedMapPropertySource.class::isInstance)
            .findFirst()
            .orElseThrow(RuntimeException::new)).getPropertyNames())
        .filter(currentValue -> StringUtils.startsWith(currentValue, BASE_PROPERTY))
        .map(key -> StringUtils.substringBetween(key, DELIMITER, DELIMITER))
        .filter(Objects::nonNull)
        .collect(Collectors.toSet());
  }
  • Related