非Spring Boot的Java Spring项目properties文件配置与读取问题
问题解决方案
问题背景
非Spring Boot的Java Spring项目中,src/main/resources/csv-convertion.properties用于填充HashMap:
- JUnit测试时能正常读取属性值
- Maven构建war包后,文件未被打包进war,运行时抛出
FileNotFoundException - 尝试在pom.xml中仅配置
src/main/java为资源目录后,程序无报错但执行读取流程时卡住,需调用其他API才恢复
错误日志
java.io.FileNotFoundException: src/main/resources/csv-convertion.properties (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.io.FileInputStream.<init>(FileInputStream.java:93) at it.egeos.aware.dm.orchestrator.config.PropertyFileReader.read(PropertyFileReader.java:15) at it.egeos.aware.dm.orchestrator.batch.base.tasklets.GeoMesaIngestFileTasklet.createSftFile(GeoMesaIngestFileTasklet.java:239) at it.egeos.aware.dm.orchestrator.batch.base.tasklets.GeoMesaIngestFileTasklet.execute(GeoMesaIngestFileTasklet.java:171) // 后续堆栈省略...
尝试过的错误配置
<build> <resources> <resource> <directory>src/main/java</directory> </resource> </resources> </build>
当前错误的读取方式
Map<String, String> properties = PropertyFileReader.read("src/main/resources/csv-convertion.properties");
解决步骤
1. 修正Maven资源配置
默认情况下src/main/resources是Maven的默认资源目录,会被自动打包到WEB-INF/classes下。之前的配置仅指定src/main/java,导致src/main/resources下的文件未被打包。恢复正确的资源配置:
<build> <resources> <!-- 确保resources目录的资源被打包 --> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> </includes> </resource> <!-- 若需要包含java目录下的资源,可添加此配置,否则删除 --> <!-- <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> </includes> </resource> --> </resources> </build>
2. 修正属性文件读取逻辑
打包后,src/main/resources的目录结构不存在,不能用相对路径读取文件,必须通过类加载器读取classpath中的资源。修改PropertyFileReader的read方法:
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class PropertyFileReader { public static Map<String, String> read(String fileName) throws IOException { Map<String, String> propertiesMap = new HashMap<>(); Properties properties = new Properties(); // 通过类加载器读取classpath中的资源,直接传入文件名即可 try (InputStream inputStream = PropertyFileReader.class.getClassLoader().getResourceAsStream(fileName)) { if (inputStream == null) { throw new IOException("Property file not found in classpath: " + fileName); } properties.load(inputStream); // 将Properties转换为HashMap for (String key : properties.stringPropertyNames()) { propertiesMap.put(key, properties.getProperty(key)); } } return propertiesMap; } }
3. 修改调用代码
调用时直接传入文件名,无需带路径:
Map<String, String> properties = PropertyFileReader.read("csv-convertion.properties");
4. 验证打包结果
执行mvn clean package构建war包,解压后检查WEB-INF/classes目录下是否存在csv-convertion.properties,确认文件已被正确打包。
内容的提问来源于stack exchange,提问作者Luigi
相关产品推荐
相关产品推荐

