如何从server.properties而非.yml文件获取并启动服务器端口?
如何让Spring应用从/config/server.properties读取端口配置
嘿,我来帮你搞定这个问题!要让你的Spring Boot应用从/config/server.properties读取端口,而不是默认的.yml文件,有几种简单的方法,我给你详细拆解:
第一步:先在配置文件里添加端口
首先确保你的/config/server.properties里已经写上了端口配置:
server.port=7799
方法一:利用Spring Boot默认配置加载优先级(最省心)
Spring Boot本身有一套配置加载的优先级规则,外部同级目录下的/config文件夹里的配置文件,优先级会高于classpath里的配置。也就是说:
- 如果你的
config/server.properties放在Jar包运行的同级目录下(比如Jar在app/,config就在app/config/) - 或者你把
config目录放在项目的src/main/resources下(打包后会被包含到classpath中)
这时候Spring Boot会自动优先读取这个server.properties里的server.port,直接覆盖.yml里的配置,不需要改任何代码!是不是超简单?
方法二:启动时通过命令行指定配置位置
如果你的config目录不在默认扫描路径里,或者你想明确指定加载这个文件,可以在启动Jar的时候添加参数:
java -jar your-application.jar --spring.config.location=classpath:/,file:./path/to/config/
把这里的file:./path/to/config/换成你实际的config目录路径,这个参数会让Spring先加载默认的classpath配置,再加载你指定的config目录下的配置,确保后者的优先级更高。
方法三:在启动类里手动加载配置(适合自定义逻辑场景)
如果你想在代码里主动控制加载这个配置文件,可以修改启动类的main方法,添加初始化器来加载server.properties,并设置它的优先级高于默认配置:
public static void main(String[] args) throws UnknownHostException { SpringApplication app = new SpringApplication(Application.class); // 手动加载/config/server.properties并设置高优先级 app.addInitializers((ApplicationContextInitializer<ConfigurableApplicationContext>) ctx -> { ConfigurableEnvironment env = ctx.getEnvironment(); Properties serverProps = new Properties(); try { // 路径根据实际情况调整,外部目录也可以用绝对路径 File configFile = new File("./config/server.properties"); serverProps.load(new FileInputStream(configFile)); // 把自定义配置源加到最前面,确保优先级最高 env.getPropertySources().addFirst(new PropertiesPropertySource("custom-server-config", serverProps)); } catch (IOException e) { log.warn("Could not load /config/server.properties, falling back to default config", e); } }); SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); addDefaultProfile(app, source); 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")); }
这样代码启动时会先尝试加载指定的properties文件,加载失败的话会自动回退到默认配置,非常稳妥。
注意事项
- 确认
/config/server.properties的路径正确:如果是项目内目录,打包时要确保该目录被包含到classpath;如果是外部目录,要保证应用有读取权限。 - 配置优先级:如果多个配置文件里都有
server.port,Spring会优先使用优先级高的那个(外部config > 内部config > classpath根目录)。
内容的提问来源于stack exchange,提问作者Bob




