Spring 启动应用程序主要方法正在执行两次 -> 端口已被使用

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

这是我第一次从头开始配置 spring 启动应用程序,整整 2 天我都在为这个问题做噩梦。 当我尝试启动应用程序时,它看起来好像在尝试启动两次,每次我都收到一个端口已被使用的错误,但进程没有停止,如果我试图用邮递员调用端点,它有效。

这是他的控制台输出:

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.

这些日志都是一样的运行。

这是我的 build.gradle 文件:

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') {
}

这里是 build.gradle 开发配置文件:

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)
        }
    }
}

主要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.");
            }
        }
    }

}

我的想法是我的构建文件有问题,但还没有找到解决方案。 有没有人遇到过同样的问题?任何解决方案的想法? 提前致谢。

您正在调用 SpringApplication::run 静态方法两次。

首先使用 SpringApplication.run(VcrawlPortalBackendApplication.class, args); 和它们来自您初始化的 SpringApplication 实例 Environment env = app.run(args).getEnvironment();

您的应用程序已经开始在端口 8187 上执行。由于您设置了 运行 方法的重复调用,它再次尝试在端口 8187 上开始执行。 解决方案 -> 删除 运行 函数的重复调用。