0

I am using below config.yml

# AWS DynamoDB settings
dynamoDB:
  # Access key
  aws_access_key_id: "access-key"
  #Secret Key
  aws_secret_access_key: "secret-key"
  aws_dynamodb_region: EU_WEST_1 

And below class to read the above config values in my DynamoDBConfig class.

public class DynamoDBConfig {
    public DynamoDBConfig() {
    }

    @JsonProperty("aws_access_key_id")
    public String accessKey;

    @JsonProperty("aws_secret_access_key")
    public String secretKey;

    @JsonProperty("aws_dynamodb_region")
    public String region;

    // getters and setters
}

Finally ApplicationConfig class which include DynamoDB config.

public class ReadApiConfiguration extends Configuration {
    @NotNull
    private DynamoDBConfig dynamoDBConfig = new DynamoDBConfig();

    @JsonProperty("dynamoDB")
    public DynamoDBConfig getDynamoDBConfig() {
        return dynamoDBConfig;
    }

    @JsonProperty("dynamoDB")
    public void setDynamoDBConfig(DynamoDBConfig dynamoDBConfig) {
        this.dynamoDBConfig = dynamoDBConfig;
    }
}

Now i want to read aws_access_key and aws_secret_key values in my AWSclient.java class to create a awsclient

BasicAWSCredentials awsCreds = new BasicAWSCredentials("access_key_id", "secret_key_id");

My problem is, how i read/inject the config values, in my AWSClient class. I am using the dropwizard-guice module for DI. and couldn't figure out , how can i bind the configuration object created at the DW startup time to its class.

P.S. :-> I've gone through this SO post but it doesn't solve my issue, as its not using guice as a DI module.

Community
  • 1
  • 1

1 Answers1

0

Normally, you can inject your configuration object either into a class field or into a constructor, like:

public class AWSclient {

  @Inject
  public AWSclient(ReadApiConfiguration conf) {
     initConnection(conf.getDynamoDBConfig().getSecretKey(), ...)
  }

}

Additionally, annotate your ReadApiConfiguration class with the @Singleton annotation.

Vyacheslav
  • 1,186
  • 2
  • 15
  • 29
  • But still i need to create the AWSClient from my application class only where `run(final ReadApiConfiguration configuration, final Environment environment) ` method has config param. how can i create from other part of the application ? –  Mar 22 '17 at 07:31
  • You don't have to create it there. Inject your AWSClient wherever you need it. Guice should take care about creating its instance and providing a configuration object into the constructor. – Vyacheslav Mar 22 '17 at 14:55
  • i need to bind AWSClient somewhere in guice-bundle correct ? i still don't understand how guice will create its instance. Could you share piece of code if any related to guice or is it done oftb? –  Mar 22 '17 at 15:31