Search code examples
javaspring-bootspring-profiles

Spring boot application main method is executing twice -> port already in use


It is my first time when I configure a spring boot application from scratch and for 2 days I was having a nightmare with this issue. When I am trying to start the application it looks like it's trying to start twice and every time I got an error that port is already in use, but the process is not stopped and if I'm trying to call an endpoint with postman, it works.

Here is he console output:

Starting Gradle Daemon...
Connected to the target VM, address: '127.0.0.1:61857', transport: 'socket'
Gradle Daemon started in 1 s 473 ms
> Task :processResources UP-TO-DATE
> Task :compileJava UP-TO-DATE
> Task :classes UP-TO-DATE
Connected to the VM started by ':VcrawlPortalBackendApplication.main()' (localhost:61879). Open the debugger session tab

> Task :VcrawlPortalBackendApplication.main()

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-02-25 15:48:19.817  INFO 471912 --- [  restartedMain] c.v.v.VcrawlPortalBackendApplication     : Starting VcrawlPortalBackendApplication on VOQCLUJWEBTS with PID 471912 
2020-02-25 15:48:19.822 DEBUG 471912 --- [  restartedMain] c.v.v.VcrawlPortalBackendApplication     : Running with Spring Boot v2.2.4.RELEASE, Spring v5.2.3.RELEASE
2020-02-25 15:48:19.823  INFO 471912 --- [  restartedMain] c.v.v.VcrawlPortalBackendApplication     : The following profiles are active: dev
2020-02-25 15:48:22.237 DEBUG 471912 --- [  restartedMain] c.v.v.config.DatabaseConfiguration       : Configuring Datasource
.........
2020-02-25 15:48:25.065  INFO 471912 --- [  restartedMain] c.v.v.VcrawlPortalBackendApplication     : Started VcrawlPortalBackendApplication in 6.273 seconds (JVM running for 6.994)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-02-25 15:48:25.178  INFO 471912 --- [  restartedMain] c.v.v.VcrawlPortalBackendApplication     : Starting VcrawlPortalBackendApplication on VOQCLUJWEBTS with PID 471912 
2020-02-25 15:48:25.179 DEBUG 471912 --- [  restartedMain] c.v.v.VcrawlPortalBackendApplication     : Running with Spring Boot v2.2.4.RELEASE, Spring v5.2.3.RELEASE
2020-02-25 15:48:25.179  INFO 471912 --- [  restartedMain] c.v.v.VcrawlPortalBackendApplication     : The following profiles are active: dev
2020-02-25 15:48:25.765 DEBUG 471912 --- [  restartedMain] c.v.v.config.DatabaseConfiguration       : Configuring Datasource
2020-02-25 15:48:25.904  INFO 471912 --- [  restartedMain] c.v.v.VcrawlPortalBackendApplication     : Running with Spring profile(s) : [dev]
2020-02-25 15:48:26.166 ERROR 471912 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Web server failed to start. Port 8187 was already in use.

Action:

Identify and stop the process that's listening on port 8187 or configure this application to listen on another port.

This logs are all at the same run.

This is my build.gradle file:

plugins {
id 'org.springframework.boot' version '2.2.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id 'war'
}

bootWar {
    mainClassName = 'com.voquz.vcrawlportalbackend.VcrawlPortalBackendApplication'
    excludeDevtools = true
}

springBoot {
    mainClassName = 'com.voquz.vcrawlportalbackend.VcrawlPortalBackendApplication'
}

bootRun {
    sourceResources sourceSets.main

    if (System.getProperty('DEBUG', 'false') == 'true') {
        jvmArgs '-Xdebug',
                '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
    }
}

if (project.hasProperty('prod')) {
    apply from: 'profile_prod.gradle'
} else if (project.hasProperty('uat')) {
    apply from: 'profile_uat.gradle'
} else {
    apply from: 'profile_dev.gradle'
}

group = 'com.voquz.vcrawl-portal-backend'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation ('org.springframework.boot:spring-boot-starter-web') {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
    }
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.liquibase:liquibase-core'
    implementation 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate4'
    implementation 'org.hibernate:hibernate-core'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    testImplementation 'org.springframework.security:spring-security-test'
    compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '8.2.0.jre8'
    compile 'com.github.sabomichal:liquibase-mssql:1.5'
    compile group: 'com.hynnet', name: 'sqljdbc-chs', version: '4.0.2206.100'
}

compileJava.dependsOn(processResources)

clean {
    delete "target"
}

task stage(dependsOn: 'bootRepackage') {
}

Here is the build.gradle file for development profile:

ext {
    logbackLoglevel = "DEBUG"
}

dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-devtools'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '2.2.4.RELEASE'
}

bootRun {
    args = ["--spring.profiles.active=dev"]
}

task setProdProperties(dependsOn: bootRun) {
    doFirst {
        System.setProperty('spring.profiles.active', 'dev')
    }
}

processResources {
    filesMatching('**/logback-spring.xml') {
        filter {
            it.replace('@logback.loglevel@', logbackLoglevel)
        }
    }
}

And the main class:

@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class})
public class VcrawlPortalBackendApplication {

    private static final Logger log = LoggerFactory.getLogger(VcrawlPortalBackendApplication.class);

    @Autowired
    private Environment environment;

    public static void main(String[] args) throws UnknownHostException {
        SpringApplication app = new SpringApplication(VcrawlPortalBackendApplication.class);
        SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
        addDefaultProfile(app, source);
        SpringApplication.run(VcrawlPortalBackendApplication.class, args);
        Environment env = app.run(args).getEnvironment();
        log.info("Access URLs:\n----------------------------------------------------------\n\t" +
                        "Local: \t\thttp://127.0.0.1:{}\n\t" +
                        "External: \thttp://{}:{}\n----------------------------------------------------------",
                env.getProperty("server.port"),
                InetAddress.getLocalHost().getHostAddress(),
                env.getProperty("server.port"));

    }

    /**
     * If no profile has been configured, set by default the "dev" profile.
     */
    private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
        if (!source.containsProperty("spring.profiles.active") &&
                !System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {

            app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
        }
    }

    @PostConstruct
    public void initApplication() {
        if (environment.getActiveProfiles().length == 0) {
            log.warn("No Spring profile configured, running with default configuration");
        } else {
            log.info("Running with Spring profile(s) : {}", Arrays.toString(environment.getActiveProfiles()));
            Collection<String> activeProfiles = Arrays.asList(environment.getActiveProfiles());
            if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION)) {
                log.error("You have misconfigured your application! " +
                        "It should not run with both the 'dev' and 'prod' profiles at the same time.");
            }
            if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_UAT)) {
                log.error("You have misconfigured your application! " +
                        "It should not run with both the 'dev' and 'uat' profiles at the same time.");
            }
            if (activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION) && activeProfiles.contains(Constants.SPRING_PROFILE_UAT)) {
                log.error("You have misconfigured your application! " +
                        "It should not run with both the 'prod' and 'uat' profiles at the same time.");
            }
        }
    }

}

My thoughts are that there is a problem with my build files, but couldn't find a solution yet. Does anyone ever faced the same problem ? Any idea for a solution ? Thanks in advance.


Solution

  • You are invoking SpringApplication::run static method twice.

    Firstly using SpringApplication.run(VcrawlPortalBackendApplication.class, args); and them from your initialized SpringApplication instance Environment env = app.run(args).getEnvironment();