Amazon AppConfig from Spring Boot

Viewed 1503
1 Answers

Here's how I've integrated AWS AppConfig into my Spring Boot project.

First, let’s make sure we have this dependency in our pom.xml:

 <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-appconfig</artifactId>
      <version>1.12.134</version>
 </dependency>

Next, let’s create a simple configuration class of our own AWS AppConfig Client:

@Configuration
public class AwsAppConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(AwsAppConfiguration.class);

    private final AmazonAppConfig appConfig;
    private final GetConfigurationRequest request;

    public AwsAppConfiguration() {
        appConfig = AmazonAppConfigClient.builder().build();
        request = new GetConfigurationRequest();
        request.setClientId("clientId");
        request.setApplication("FeatureProperties");
        request.setConfiguration("JsonProperties");
        request.setEnvironment("dev");
    }

    public JSONObject getConfiguration() throws UnsupportedEncodingException {
        GetConfigurationResult result = appConfig.getConfiguration(request);
        String message = String.format("contentType: %s", result.getContentType());
        LOGGER.info(message);

        if (!Objects.equals("application/json", result.getContentType())) {
            throw new IllegalStateException("config is expected to be JSON");
        }

        String content = new String(result.getContent().array(), "ASCII");
        return new JSONObject(content).getJSONObject("feature");
    }
}

Lastly, let’s create a scheduled task that polls the configuration from AWS AppConfig:

@Configuration
@EnableScheduling
public class AwsAppConfigScheduledTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(AwsAppConfigScheduledTask.class);

    @Autowired
    private FeatureProperties featureProperties;

    @Autowired
    private AwsAppConfiguration appConfiguration;

    @Scheduled(fixedRate = 5000)
    public void pollConfiguration() throws UnsupportedEncodingException {
        LOGGER.info("polls configuration from aws app config");
        JSONObject externalizedConfig = appConfiguration.getConfiguration();
        featureProperties.setEnabled(externalizedConfig.getBoolean("enabled"));
        featureProperties.setLimit(externalizedConfig.getInt("limit"));
    }

}

I came across this question, as I was also trying to figure out how to best integrate AWS AppConfig into Spring Boot.

Here's an article I created. You can visit it here: https://levelup.gitconnected.com/create-features-toggles-using-aws-appconfig-in-spring-boot-7454b122bf91

Also, the source code is available on github: https://github.com/emyasa/medium-articles/tree/master/aws-spring-boot/app-config

Related