人类文化的悲哀,是流俗的易传、高雅的失传。——木心

我们可以如下写法在boot项目启动时获取端口号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.ruben.simplescaffold;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

/**
* 主启动类
*
* @author <achao1441470436@gmail.com>
* @since 2021/5/18 0018 14:52
*/
@Slf4j
@SpringBootApplication
public class SimpleScaffoldApplication {

public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SimpleScaffoldApplication.class, args);
Environment environment = context.getBean(Environment.class);
log.info("端口号:{}", environment.getProperty("server.port"));
}

}

获取到端口号后我们可以存储起来供其他地方使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.ruben.simplescaffold;

import cn.hutool.core.lang.SimpleCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.util.HashMap;

/**
* 主启动类
*
* @author <achao1441470436@gmail.com>
* @since 2021/5/18 0018 14:52
*/
@Slf4j
@SpringBootApplication
public class SimpleScaffoldApplication {

public static final SimpleCache<String, Object> POOL = new SimpleCache<>(new HashMap<>());

public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SimpleScaffoldApplication.class, args);
Environment environment = context.getBean(Environment.class);
String port = environment.getProperty("server.port");
POOL.put("port", port);
log.info("端口号:{}", POOL.get("port"));
}

}