How do I convert values from environment variables from string to int to use as application properties in my Spring Boot application?

Viewed 2951

I have a dockerized Spring Cloud Stream service, and I'm trying to read values for instanceCount and instanceIndex from environment variables set on the virtual machine on which the service is running. I have a class marked with the @ConfigurationProperties annotation:

package com.hines.james.converters;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("spring.cloud.stream")
public class NodeSpringCloudStreamProperties {
    private int instanceCount;
    private int instanceIndex;

    public int getInstanceCount() {
        return instanceCount;
    }

    public void setInstanceCount(int instanceCount) {
        this.instanceCount = instanceCount;
    }

    public int getInstanceIndex() {
        return instanceIndex;
    }

    public void setInstanceIndex(int instanceIndex) {
        this.instanceIndex = instanceIndex;
    }
}

and a converter:

package com.hines.james.converters;

import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
@ConfigurationPropertiesBinding
public class StringToIntegerConverter implements Converter<String, Integer>{
    @Override
    public Integer convert(String source) {
        return Integer.valueOf(source);
    }
}

and my application.yml:

spring:
  cloud:
    stream:
      instanceCount: ${NUM_NODES}
      instanceIndex: ${NODE_INDEX}

values for NUM_NODES and NODE_INDEX for this particular vm have been set in a previous step.

When I debug the service through my IDE, I can see that values are being set for instanceCount and instanceIndex. When I deploy the app, I get a ConverterNotFoundException, with this message (there's a similar message for NUM_NODES):

Field error in object 'spring.cloud.stream' on field 'instanceIndex': rejected value [${NODE_INDEX}]; codes [typeMismatch.spring.cloud.stream.instanceIndex,typeMismatch.instanceIndex,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spring.cloud.stream.instanceIndex,instanceIndex]; arguments []; default message [instanceIndex]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'instanceIndex'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [int]]

I'm using docker compose to define my multi container application, and docker swarm to deploy it.

How do I convert values from environment variables from string to int to use as application properties in my Spring Boot application?

0 Answers
Related