Spring Boot打包运行报错:无法找到Configuration.properties文件求助
解决Spring Boot打包后找不到类路径配置文件的问题
嘿,刚接触Spring Boot遇到这种问题太正常了,我来帮你搞定~
为啥会报错?
你现在用的FileReader("Configuration.properties")是基于本地文件系统路径来查找文件的,它会去你运行程序的当前工作目录找这个文件。但当你把Spring Boot项目打包成jar包后,Configuration.properties是嵌入在jar包内部的,不是文件系统上的独立文件,所以自然就找不到啦!
几种可行的解决办法
方法1:用Spring Boot自带的配置注入(最推荐)
既然用了Spring Boot,完全不用自己写Properties读取逻辑,直接用框架提供的方式更省心:
- 如果只是读取单个配置值,用
@Value注解直接注入:@RestController public class DemoController { // 假设你的配置文件里有个键叫app.name @Value("${app.name}") private String appName; // 业务逻辑里直接用appName就行 } - 如果要读取一组相关配置,用
@ConfigurationProperties绑定到实体类:
注意:如果你的配置文件名不是Spring Boot默认的// 配置类,绑定前缀为app的所有配置 @ConfigurationProperties(prefix = "app") @Component public class AppConfig { private String name; private String version; // 记得加getter和setter public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } } // 在其他类里注入使用 @Service public class DemoService { @Autowired private AppConfig appConfig; public void doSomething() { System.out.println(appConfig.getName()); } }application.properties,需要在启动类上加上@PropertySource("classpath:Configuration.properties"),让Spring识别到这个配置文件。
方法2:手动读取类路径资源(如果一定要自己写读取逻辑)
要是你确实需要手动加载Properties文件,别再用FileReader了,改用Spring的ClassPathResource或者类加载器来读取:
- 用
ClassPathResource的方式:public static Properties readProperties() throws IOException { // 从类路径加载资源 ClassPathResource resource = new ClassPathResource("Configuration.properties"); Properties props = new Properties(); // 通过输入流读取,不管是在IDE里运行还是打包成jar都能正常读取 props.load(resource.getInputStream()); return props; } - 或者用类加载器的方式(带自动关流的写法):
public static Properties readProperties() throws IOException { // 获取当前线程的上下文类加载器 try (InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("Configuration.properties")) { Properties props = new Properties(); props.load(inputStream); return props; } }
小提醒
尽量优先用Spring Boot提供的配置管理方式,不仅能避免路径问题,还能享受框架带来的配置自动刷新、类型转换等便利功能哦~
内容的提问来源于stack exchange,提问作者Albin Chandy
相关产品推荐
相关产品推荐

