租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

spring如何获取项目根目录,spring获取文件

发布时间:2023-12-23 19:03:12

spring如何获得项目根目录

在Spring中获得项目根目录有多种方式:

  1. 使用System.getProperty()方法获得user.dir属性,该属性表示当前工作目录,即项目根目录。
String rootDirectory = System.getProperty("user.dir");
  1. 使用ServletContext对象获得项目根目录。
@Autowired
private ServletContext servletContext;

public String getRootDirectory() {
    String rootDirectory = servletContext.getRealPath("/");
    return rootDirectory;
}
  1. 使用ResourceLoader对象获得项目根目录。
@Autowired
private ResourceLoader resourceLoader;

public String getRootDirectory() {
    Resource resource = resourceLoader.getResource("classpath:");
    String rootDirectory = resource.getFile().getAbsolutePath();
    return rootDirectory;
}

注意:以上方法都是在Spring MVC或Spring Boot项目中获得项目根目录的方式,如果是普通的Spring项目,可能需要进行适当的调剂。