You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Spring Boot服务器URL写入静态文件?

将Spring Boot服务器URL写入静态文件的可行方法

当然可以实现,下面提供两种实用的方案,都是在Spring Boot启动完成后自动获取服务器URL并写入指定文件:

方法一:监听ApplicationReadyEvent事件

Spring Boot启动完成后会发布ApplicationReadyEvent事件,通过监听这个事件可以安全获取服务器的端口和地址信息,再写入目标文件。

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class ServerUrlWriter implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 获取配置的服务器端口,默认8080
        int port = event.getApplicationContext().getEnvironment()
                .getProperty("server.port", Integer.class, 8080);
        // 获取主机地址,失败时 fallback 到localhost
        String host;
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            host = "localhost";
        }
        String serverUrl = String.format("http://%s:%d", host, port);
        
        // 写入指定文件,开发环境可直接写resources目录;打包运行时建议改为外部路径
        String filePath = "src/main/resources/server-url.txt";
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(serverUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

方法二:使用CommandLineRunner

CommandLineRunner会在Spring Boot应用启动完成后执行,适合简单的启动后任务,同样可以实现需求:

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class ServerUrlRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        int port = Integer.parseInt(System.getProperty("server.port", "8080"));
        String host;
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            host = "localhost";
        }
        String serverUrl = String.format("http://%s:%d", host, port);
        
        String filePath = "src/main/resources/server-url.txt";
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(serverUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

关键注意事项

  • 如果应用打包成Jar运行,不要写入Jar内部的resources目录(Jar是压缩文件,运行时无法修改内部内容),建议改为写入Jar外部的路径,比如./server-url.txt。
  • 若应用部署在集群或使用反向代理,需要根据实际场景调整host的获取逻辑,比如从环境变量、配置中心读取外部可访问的域名/IP。

内容的提问来源于stack exchange,提问作者hoiskipoiski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:16:27