Spring Boot では、設定ファイルのパスを取得する方法は何ですか?

Spring Bootでは、ResourceLoaderを使用して設定ファイルのパスを取得することができます。ResourceLoaderをクラスに注入し、getResource()メソッドを使用して設定ファイルのパスを取得することができます。

こちらは日本語でネイティブに言い換えた例です。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

@Component
public class ConfigFilePathProvider {
    
    @Autowired
    private ResourceLoader resourceLoader;

    public String getConfigFilePath() {
        Resource resource = resourceLoader.getResource("classpath:application.properties");
        return resource.getURI().getPath();
    }
}

上記の例では、ResourceLoaderが自動的に設定ファイルをロードし、getResource()メソッドを使用してResourceオブジェクトを取得します。getURI()。getPath()メソッドを使用して、設定ファイルのパスを取得できます。

注意:上記の例で示されているclasspath:application.propertiesは単なる例ですので、実際の設定ファイル名に置き換えてください。

bannerAds