'Pass Dynamic Port from Gradle boot:run of an application

I am having an application, which is running on some port(ex-8080) now when I start this application using gradlew I want to pass dynamic port to start the application?

./gradlew :testApplication:bootRun

is there anyway to pass the dynamic port here??



Solution 1:[1]

Add the following to build.gradle so that we can pass parameters to gradlew along to the underlying java command:

bootRun {
    if (project.hasProperty('args')) {
        args project.args.split(',')
    }
}

Pass the arguments you would normally send to a java command (in this case, overriding the server.port) as -Pargs to gradlew:

/gradlew :testApplication:bootRun -Pargs="--server.port=8081"

What is here:

  • When you run java with arguments --server.port=8081, Spring Boot will override default property (e.g. Spring Boot will ignore your port in properties file, it will use value from command line
  • -Pargs is the way to ask bootRun to command line arguments. See details here.

See also the same question for maven.

Solution 2:[2]

I couldn't pass the port directly.

But if you want a workaround, do the following:

  • Build the application with gradle build.
  • Navigate in your project and open the directory build/libs
  • Now you have to see the jar of your project and then run this command java -jar yourJarProject.jar --server.port=8081.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris Trevarthen
Solution 2