0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Gradleでdotenvを利用する

Last updated at Posted at 2020-05-07

npmでよく利用されているdotenvをGradleでも使えないか試してみたよ。

build.gradleに下記の記述を追加する

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "co.uzzu.dotenv:gradle:1.1.0"
  }
}

apply plugin: "co.uzzu.dotenv.gradle"

プロジェクトルートに.envファイルを作成する

中身は適当にこんなかんじで。

FOO=foo

値を取得するには

環境変数名を指定するとOptional型が返ってくるので準じた方法で値を取得する。
環境変数が定義されていない場合ビルドエラーになるケースがあるので、fetchOrNull()を利用するのが良さげ。

env.FOO.value                     // => foo
env.fetch('FOO')                  // => foo
env.HOGE.value                    // => ビルドエラー
env.fetch('HOGE')                 // => ビルドエラー
env.fetchOrNull('FOO')            // => foo
env.fetchOrNull('HOGE')           // => null
env.fetch('HOGE', 'defaultValue') // => defaultValue

全ての環境変数をMapで取得するメソッド等もあります。
そのへんの詳細はプラグインのGithubを参照してください。

利用しているプラグイン

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?