springでは、プロジェクトのルートディレクトリを取得する方法は?
Springでプロジェクトのルートディレクトリを取得する方法は複数あります。
- システムのプロパティを取得する
- 現在のユーザーディレクトリ
String rootDirectory = System.getProperty("user.dir");
- サーブレットコンテキスト
@Autowired
private ServletContext servletContext;
public String getRootDirectory() {
String rootDirectory = servletContext.getRealPath("/");
return rootDirectory;
}
- リソースローダー
@Autowired
private ResourceLoader resourceLoader;
public String getRootDirectory() {
Resource resource = resourceLoader.getResource("classpath:");
String rootDirectory = resource.getFile().getAbsolutePath();
return rootDirectory;
}
注:上記の方法は、Spring MVCまたはSpring Bootプロジェクトでプロジェクトのルートディレクトリを取得する方法です。通常のSpringプロジェクトの場合は、適切な調整が必要かもしれません。