如果不指定绝对路径,会抛出 FieNotFoundException
我尝试了以下路径:
../../../resources/connection.properties
src/main/resources/connection.properties
web/src/main/resources/connection.properties
connection.properties
resources/connection.properties
这是他写的:
Caused by: java.io.FileNotFoundException: ***my attempts*** (The system cannot find the path specified)
项目即将开战
如何指定相对路径?
问题来源:
@Service
public class SocketConnectionPropertiesLoader implements ConnectionPropertiesLoader {
@Override
public Properties loadProperties(String pathToProperties) {
File file = new File(pathToProperties);
Properties properties = new Properties();
try {
properties.load(new FileReader(file));
return properties;
} catch (IOException e) {
throw new SocketConnectionException(e);
}
}
}
我也试过把资源文件夹转移到WEB-INF,可惜也没成功

如果文件在您项目的资源中,那么您可以这样做:
如果文件在 root
resources中,那么 spring 会自动嵌入它。接下来,使用getFile类型的 Resource 方法来获取内容。这里的关键点(以及在您的尝试中不起作用的地方):
getClass().getResourceAsStream("/connection.properties")这就是 spring 所做的)。Resource但特别是对于属性,使用起来更方便
PropertySource:然后在其他bean中使用
@Value或:@InjectConnectionProperties从示例中,必须要么在属于自动配置扫描的包中,要么通过@Import.