简体   繁体   中英

How do you get passwords from maven settings or gradle properties into your java/kotlin code at build time?

You aren't supposed to put passwords or api keys into your code. Definitely don't check them into source control! Both maven and gradle have ways to store private stuff in your home folder and incorporate passwords at build time. People use this to deploy to Maven Central/Sonatype. But wouldn't this be the perfect place to store passwords that get used in your code? Like the database password or keystore password?

Is there a way to incorporate something into your code at build time so your java code could say something like:

  private static final String myPw = "$$maven.settings.servers.server[ossrh].password$$";

So that your build tool would substitute it on the fly so it ends up in your bytecode, but not in your source code, or source repository? A Java or Kotlin annotation perhaps?

Step 1: Create file during compilation

tasks.withType<ProcessResources> {
    doLast {
        File("$buildDir/resources/main/build.properties").writeText("""
            version=${someVariable}
        """.trimIndent())
    }
}

Step 2: Read during Runtime

object BuildInfo {
    val VERSION: String

    init {
        // build.properties file will be generated by gradle
        val buildProps = Properties()
        buildProps.load(ClassPathResource("build.properties").inputStream)
        VERSION = buildProps["version"] as String
    }
}

You can access this via BuildInfo.VERSION

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM