springboot怎么获取resource路径
导读:在Spring Boot中获取resource路径有多种方式: 使用ClassPathResource类:可以通过ClassPathResource类获取classpath下的资源路径。例如,可以使用以下代码获取classpath下的co...
在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下资源的路径。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: springboot怎么获取resource路径
本文地址: https://pptw.com/jishu/609071.html