Spring boot 如何在应用程序属性-Spring引导中设置文件位置

Spring boot 如何在应用程序属性-Spring引导中设置文件位置,spring-boot,properties,path,Spring Boot,Properties,Path,我有一个Spring启动应用程序,代码需要访问resources/templates文件夹下的文件。 这是我的application.properties文件: pont.email.template.location=templates/mailTemplate.html 这是我使用变量的java文件: @Value("${pont.email.template.location}") private String templateLocation; ---

我有一个Spring启动应用程序,代码需要访问resources/templates文件夹下的文件。 这是我的application.properties文件:

    pont.email.template.location=templates/mailTemplate.html
这是我使用变量的java文件:

    @Value("${pont.email.template.location}") 
    private String templateLocation;
    ----------------
    BufferedReader reader = new BufferedReader(new FileReader(templateLocation));
问题在于无法获取varibale,它会正确返回,问题在于应用程序找不到此路径的任何文件

我总是很紧张

    java.io.FileNotFoundException: templates/mailTemplate.html (No such file or directory)
我已检查文件是否在路径中

我的代码有什么问题?
请帮忙,谢谢。

你不能从罐子里读取
文件。这会失败,因为
文件
必须指向文件系统上的实际文件资源,而不是JAR中的某个内容

让Spring来完成繁重的工作,并使用抽象来隐藏讨厌的内部结构。因此,不要使用
字符串
而是使用
资源
并在属性值前面加上
类路径:
,以确保它是从类路径加载的。然后使用
InputStreamReader
而不是
FileReader
来获取所需信息

@Value("${pont.email.template.location}") 
private Resource templateLocation;
----------------
BufferedReader reader = new BufferedReader(new InputStreamReader(templateLocation.getInputStream()));
应用程序中.properties
前缀为
类路径:

pont.email.template.location=classpath:templates/mailTemplate.html

现在,无论您运行的环境如何,它都应该可以工作

可能是,请尝试classpath:templates/mailTemplate.htmlc考虑到错误发生在尝试读取文件时,您现在发布的代码相关性较小。请共享用于读取文件的代码,并将其添加到问题中。@Cooshal此路径返回相同的错误:java.io.FileNotFoundException:classpath:templates/mailTemplate.html(没有此类文件或目录)@g00glen00b已完成,谢谢!这个文件的确切位置是什么?是不是
src/main/resources/templates
?非常感谢@戴纳姆先生,这锅我做得很好!