在Spring Boot中获取resource路径有多种方式:
- 使用
ClassPathResource
类:可以通过ClassPathResource
类获取classpath下的资源路径。例如,可以使用以下代码获取classpath下的config.properties
文件路径:
ClassPathResource resource = new ClassPathResource("config.properties");
String path = resource.getFile().getAbsolutePath();
- 使用
ResourceLoader
接口:通过注入ResourceLoader
接口,可以使用getResource
方法获取资源路径。例如,可以使用以下代码获取classpath下的config.properties
文件路径:
@Autowired
private ResourceLoader resourceLoader;
public void getResourcePath() {
Resource resource = resourceLoader.getResource("classpath:config.properties");
String path = resource.getFile().getAbsolutePath();
}
- 使用
@Value
注解:可以使用@Value
注解将资源路径注入到变量中。例如,可以使用以下代码获取classpath下的config.properties
文件路径:
@Value("classpath:config.properties")
private Resource resource;
public void getResourcePath() {
String path = resource.getFile().getAbsolutePath();
}
无论使用哪种方式,都可以获取到classpath下资源的路径。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/849006.html