springでは、プロジェクトのルートディレクトリを取得する方法は?

Springでプロジェクトのルートディレクトリを取得する方法は複数あります。

  1. システムのプロパティを取得する
  2. 現在のユーザーディレクトリ
String rootDirectory = System.getProperty("user.dir");
  1. サーブレットコンテキスト
@Autowired
private ServletContext servletContext;

public String getRootDirectory() {
    String rootDirectory = servletContext.getRealPath("/");
    return rootDirectory;
}
  1. リソースローダー
@Autowired
private ResourceLoader resourceLoader;

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

注:上記の方法は、Spring MVCまたはSpring Bootプロジェクトでプロジェクトのルートディレクトリを取得する方法です。通常のSpringプロジェクトの場合は、適切な調整が必要かもしれません。

bannerAds