Mar*_*pez 3 properties path spring-boot
我有一个 Spring Boot 应用程序,代码需要访问资源/模板文件夹下的文件。这是我的 application.properties 文件:
pont.email.template.location=templates/mailTemplate.html
Run Code Online (Sandbox Code Playgroud)
这是我使用变量的java文件:
@Value("${pont.email.template.location}")
private String templateLocation;
----------------
BufferedReader reader = new BufferedReader(new FileReader(templateLocation));
Run Code Online (Sandbox Code Playgroud)
问题不是获取变量,而是正确返回,问题是应用程序没有找到该路径的任何文件。
我总是得到
java.io.FileNotFoundException: templates/mailTemplate.html (No such file or directory)
Run Code Online (Sandbox Code Playgroud)
我已经检查过文件在路径中..
我的代码有什么问题?请帮忙,谢谢。
您不能File从 JAR 内部读取 a 。由于 必须File指向文件系统上的实际文件资源而不是 JAR 中的内容,因此这会失败。
让 Spring 完成繁重的工作并使用Resource抽象来隐藏讨厌的内部结构。因此,不要使用Stringuse aResource并将属性值作为前缀,classpath:以确保它是从类路径加载的。然后使用InputStreamReader代替FileReader来获取您需要的信息。
@Value("${pont.email.template.location}")
private Resource templateLocation;
----------------
BufferedReader reader = new BufferedReader(new InputStreamReader(templateLocation.getInputStream()));
Run Code Online (Sandbox Code Playgroud)
在你的application.properties前缀中classpath:。
pont.email.template.location=classpath:templates/mailTemplate.html
Run Code Online (Sandbox Code Playgroud)
现在,无论您在什么环境中运行,它都应该可以工作。