springboot怎么獲取resource路徑

小億
467
2024-02-01 13:14:39

在Spring Boot中獲取resource路徑有多種方式:

  1. 使用ClassPathResource類:可以通過(guò)ClassPathResource類獲取classpath下的資源路徑。例如,可以使用以下代碼獲取classpath下的config.properties文件路徑:
ClassPathResource resource = new ClassPathResource("config.properties");
String path = resource.getFile().getAbsolutePath();
  1. 使用ResourceLoader接口:通過(guò)注入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();
}

無(wú)論使用哪種方式,都可以獲取到classpath下資源的路徑。

0