Springboot项目中获取当前服务端口号

该博客介绍了如何在Spring Boot应用启动时排除DataSourceAutoConfiguration并获取服务器的端口号。通过实现ApplicationListener接口监听WebServerInitializedEvent事件,获取到Web服务器的端口,并提供了静态方法获取请求基地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 启动时获取

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class AdminApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(AdminApplication.class);
        Environment env = app.run( args).getEnvironment();
        System.out.println(env.getProperty("server.port"));
    }
}

2. ApplicationListener接口

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class ServiceConfig implements ApplicationListener<WebServerInitializedEvent> {
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        // 项目启动获取启动的端口号
        ServiceConfig.serverPort = event.getWebServer().getPort();
    }

    /**
     * 当前服务使用的端口号
     */
    private static int serverPort;

    public static int getServerPort() {
        return serverPort;
    }

    public void setServerPort(int serverPort) {
        ServiceConfig.serverPort = serverPort;
    }

    /**
     * 获取请求基地址
     *
     * @return String 请求基地址
     * @date 2021/11/15
     **/
    public static String getBaseUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://"+address.getHostAddress() +":"+ getServerPort();
    }
}
### Spring Boot 启动文件配置及作用 #### 1. **SpringApplication 类的作用** `org.springframework.boot.SpringApplication` 是 Spring Boot 的核心启动类,在创建 `SpringApplication` 实例时,会执行一系列初始化操作。这包括设置运行环境、注册监听器以及解析命令行参数等[^1]。 #### 2. **配置加载阶段** 在 Spring Boot 启动过程中,配置文件的加载是一个重要环节。Spring Boot 支持多种格式的配置文件,主要包括 `.properties` 和 `.yml` 文件。默认情况下,Spring Boot 使用 `application.properties` 或 `application.yml` 来存储应用级别的全局配置[^3]。 以下是常见的配置文件及其功能: - **application.properties** 这是最常用的配置文件之一,默认位于项目的 `src/main/resources/` 目录下。它用于定义应用程序的各种属性,例如服务器端口、数据源配置、日志级别等[^4]。 - **application.yml** YAML 格式的配置文件提供了更简洁的方式来管理嵌套结构的数据。它的语法更加直观,适合复杂的分层配置场景[^4]。 #### 3. **配置文件加载顺序** Spring Boot 按照一定的优先级顺序来加载配置文件。通常来说,外部化的配置具有更高的优先级,这意味着它们可以覆盖内部默认值或其他较低优先级的配置[^1]。具体的加载顺序如下: 1. 命令行参数 (`--server.port=8081`)。 2. Java 系统属性 (System.getProperties())。 3. 操作系统环境变量。 4. 当前目录下的 `config/` 子目录中的 `application.properties` 或 `application.yml`。 5. 当前目录下的 `application.properties` 或 `application.yml`。 6. classpath 中的 `/config/` 下的 `application.properties` 或 `application.yml`。 7. classpath 根路径下的 `application.properties` 或 `application.yml`。 #### 4. **常用配置项** 开发者可以通过官方文档获取完整的配置列表[^2]。以下是一些典型的配置示例: - 设置服务端口号: ```properties server.port=8090 ``` - 数据库连接配置(以 MySQL 为例): ```properties spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` - 日志级别调整: ```properties logging.level.org.springframework.web=DEBUG ``` #### 5. **动态切换配置文件** 为了适应不同的部署环境(如开发、测试、生产),Spring Boot 提供了多环境配置的支持。通过激活特定的 profile,可以选择对应的配置文件。例如: ```properties spring.profiles.active=dev ``` 此时,程序将会加载名为 `application-dev.properties` 或 `application-dev.yml` 的额外配置文件,并将其与通用配置合并[^3]。 --- ### 示例代码:自定义端口并启用调试模式 下面展示如何在一个简单的 Spring Boot 项目中修改默认端口并开启调试日志记录: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 对应的应用配置文件内容如下: ```properties # application.properties server.port=8085 logging.level.root=DEBUG ``` 或者使用 YAML 格式: ```yaml # application.yml server: port: 8085 logging: level: root: DEBUG ``` ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值