akerra
akerra

Reputation: 1200

Guice injecting empty string instead of value from @Provides method

I have the following class which is using Lombok-generated constructor injection:

@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class S3ModelAuditor implements ModelAuditor {

    private final S3Client s3Client;
    @Named(MODEL_AUDIT_BUCKET_NAME)
    private final String bucketName;

    ... class methods...
}

Then in my module, I bind the implementation to the interface, and also have the necessary provider methods for the constructor args:

public class PluginModule extends AbstractModule {

    public static final String MODEL_AUDIT_BUCKET_NAME = "MODEL_AUDIT_BUCKET_NAME";

    @Override
    protected void configure() {
        super.configure();
        bind(ModelAuditor.class).to(S3ModelAuditor.class);
    }

    @Provides
    @Named(MODEL_AUDIT_BUCKET_NAME)
    public String getModelAuditBucketName() {
        String bucketName = System.getenv("MODEL_AUDIT_BUCKET");
        Objects.requireNonNull(bucketName, "MODEL_AUDIT_BUCKET environment variable is required");
        return bucketName;
    }

    @Provides
    @Singleton
    public S3Client getS3Client(@Named(PLUGIN_CREDENTIALS_NAME) final AwsCredentialsProvider credentialsProvider) {
        return S3Client.builder()
                .credentialsProvider(credentialsProvider)
                .build();
    }

    ... other provider methods ...
}

When calling S3 put object API, I get the following error, showing that the runtime value of bucketName is an empty String (I understand this to be the Guice default for string if no explicit binding is found)

software.amazon.awssdk.core.exception.SdkClientException: Unable to marshall request to JSON: Bucket cannot be empty.

Yes, I'm setting the bucket field on the S3 request:

PutObjectRequest request = PutObjectRequest.builder()
                .bucket(bucketName)
                .key(key)
                .build();

Any ideas why the getModelAuditBucketName provider method does not appear to be getting invoked? I have checked the environment variables, and the value is set correctly (a non-empty string). Using Guice 7 with Jakarta annotations.

Upvotes: 0

Views: 54

Answers (0)

Related Questions