springboot怎么获取resource路径

406
2024/2/22 13:14:39
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Spring Boot中获取resource路径有多种方式:

  1. 使用ClassPathResource类:可以通过ClassPathResource类获取classpath下的资源路径。例如,可以使用以下代码获取classpath下的config.properties文件路径:
ClassPathResource resource = new ClassPathResource("config.properties");
String path = resource.getFile().getAbsolutePath();
  1. 使用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();
}
  1. 使用@Value注解:可以使用@Value注解将资源路径注入到变量中。例如,可以使用以下代码获取classpath下的config.properties文件路径:
@Value("classpath:config.properties")
private Resource resource;

public void getResourcePath() {
    String path = resource.getFile().getAbsolutePath();
}

无论使用哪种方式,都可以获取到classpath下资源的路径。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: SpringBoot读取properties有哪些技巧