1
2

More than 3 years have passed since last update.

【Gradle】外部ライブラリの導入で詰まった話

Posted at

背景と事象

こちらの記事を参考にAWSのS3にプライベートなMavenリポジトリを作成しようとしていました。

その際に、AWSのクレデンシャル情報を取得するために

ext {
    awsCredentials = new ProfileCredentialsProvider().credentials
}

とProfileCredentialsProviderクラスを用いようとしたところ、

Could not compile build file 'C:\hoge\build.gradle'.
> startup failed:
  build file 'C:\hoge\build.gradle': 12: unable to resolve class ProfileCredentialsProvider
   @ line 12, column 23.
                awsCredentials = new ProfileCredentialsProvider().credentials
                           ^

  1 error

とビルドエラーが発生しました。

解決方法

下記のようにbuild.gradle内にbuildscriptとimport文を記述します。

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.amazonaws:aws-java-sdk-core:1.11.723'
    }

}

import com.amazonaws.auth.profile.ProfileCredentialsProvider

こうすることで、build.gradle内で外部ライブラリを用いることができます。

最終的にはこのように書くことで無事にビルドに成功し、S3にプライベートなMavenリポジトリを作成することができました。

build.gradle
buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.amazonaws:aws-java-sdk-core:1.11.723'
    }
}

import com.amazonaws.auth.profile.ProfileCredentialsProvider

apply plugin: 'java'
apply plugin: 'maven-publish'

group = 'com.hoge'
version = '1.0.0'

sourceCompatibility = '1.8'
targetCompatibility = '1.8'

compileJava {
    options.encoding = 'UTF-8'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation('省略')
    testCompile 'junit:junit:4.12'
    testCompile 'org.hamcrest:hamcrest-library:1.3'
}

ext {
    awsCredentials = new ProfileCredentialsProvider().credentials
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }

    repositories {
        maven {
            url "s3://hoge/fuga/"
            credentials(AwsCredentials) {
                accessKey awsCredentials.AWSAccessKeyId
                secretKey awsCredentials.AWSSecretKey
            }
        }
    }
}

まとめ

build.gradle内で外部ライブラリを使用する際は下記の例のように、buildscript内で使用するライブラリを宣言し、import文を書いてみてください。

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.amazonaws:aws-java-sdk-core:1.11.723'
    }

}

import com.amazonaws.auth.profile.ProfileCredentialsProvider

本記事が少しでも誰かのお役に立てば幸いです。
最後までお読み頂きありがとうございました。

参考文献

公式ドキュメント

Build Script Basics - External dependencies for the build script

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2