如何将外部配置文件用作Resource Bundle?Spring环境报错排查
问题分析与解决方案
核心问题
你用--spring.config.name和--spring.config.location指定了外部Spring配置文件,但代码里用ResourceBundle.getBundle()读取配置——这两者属于完全独立的配置体系:
- Spring的启动参数是给Spring容器识别的,用来加载Spring上下文的配置;
ResourceBundle是JDK原生的资源加载工具,它只会从JVM的类路径、或者系统属性java.ext.dirs/java.class.path指定的路径中查找资源,完全不识别Spring的配置参数,所以找不到你放在外部的myConfig.properties。
解决方案
根据你的需求(无需重新打包即可修改配置),推荐两种方案:
方案1:使用Spring原生方式读取配置(推荐)
既然已经用了Spring,直接利用Spring的配置加载机制,它会自动识别你启动时指定的外部配置文件:
- 方式一:通过
Environment对象读取
import org.springframework.core.env.Environment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class YourComponent { @Autowired private Environment env; public void getConfig() { String personTable = env.getProperty("tbl.person"); // 使用配置值 } }
- 方式二:通过
@Value注解注入
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class YourComponent { @Value("${tbl.person}") private String personTable; // 直接使用personTable变量 }
方案2:手动加载外部Properties文件(如果非要用JDK原生方式)
如果坚持不用Spring的配置机制,可以手动加载外部文件,而不是依赖ResourceBundle:
import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class ConfigReader { public static void main(String[] args) { Properties props = new Properties(); // 注意路径要和启动参数里的一致 String configPath = "C:\\Desktop\\myConfigs\\myConfig.properties"; try (FileInputStream fis = new FileInputStream(configPath)) { props.load(fis); String personTable = props.getProperty("tbl.person"); System.out.println(personTable); } catch (IOException e) { e.printStackTrace(); } } }
如果想让路径更灵活,可以把配置路径作为JVM系统参数传入(启动时加-Dconfig.path=C:\\Desktop\\myConfigs\\myConfig.properties),然后代码里用System.getProperty("config.path")获取路径。
为什么System.getProperty()没效果?
你之前尝试的System.getProperty()拿的是JVM系统参数,而--spring.config.location是Spring应用的命令行参数,不属于JVM系统参数范畴。如果要通过System.getProperty()获取它,需要在启动时改成-Dspring.config.location="file:///C:\\Desktop\\myConfigs\\"(加-D前缀),但即使拿到这个路径,ResourceBundle也不会用它来加载文件,所以还是得用上面的方案。
内容的提问来源于stack exchange,提问作者dissidia
相关产品推荐
相关产品推荐

