web-dev-qa-db-ja.com

Springのapplication.propertiesで相対パスを指定する

以下に指定されているように、Springブートアプリケーションのapplication.propertiesファイルの相対パスを使用してファイルリソースを検索できる方法はありますか

spring.datasource.url=jdbc:hsqldb:file:${project.basedir}/db/init
14

@membersoundの答えは、ハードコードされたパスを2つの部分に分割するだけで、プロパティを動的に解決するものではありません。私はあなたが探しているものを達成する方法をあなたに教えることができますが、あなたが理解している必要があるのは[〜#〜] no [〜#〜]project.basedir jarまたはwarとしてアプリケーションを実行する。ローカルワークスペースの外には、ソースコード構造は存在しません。

テストのためにこれを行いたい場合、それは実行可能であり、必要なのはPropertySourcesを操作することです。最も簡単なオプションは次のとおりです。

ApplicationContextInitializerを定義し、そこにプロパティを設定します。次のようなもの:

    public class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext appCtx) {
        try {
            // should be /<path-to-projectBasedir>/build/classes/main/
            File pwd = new File(getClass().getResource("/").toURI());
            String projectDir = pwd.getParentFile().getParentFile().getParent();
            String conf = new File(projectDir, "db/init").getAbsolutePath();
            Map<String, Object> props = new HashMap<>();
            props.put("spring.datasource.url", conf);
            MapPropertySource mapPropertySource = new MapPropertySource("db-props", props);
            appCtx.getEnvironment().getPropertySources().addFirst(mapPropertySource);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }}

Bootを使用しているようなので、context.initializer.classes=com.example.MyApplicationContextInitializerapplication.propertiesを宣言するだけで、Bootは起動時にこのクラスを実行します。

注意事項再度:

  1. これは、ソースコードの構造に依存するため、ローカルワークスペースの外では機能しません。

  2. ここではGradleプロジェクトの構造を/build/classes/mainと想定しています。必要に応じて、ビルドツールに応じて調整します。

  3. MyApplicationContextInitializersrc/test/Java内にある場合、pwd<projectBasedir>/build/classes/test/であり、<projectBasedir>/build/classes/main/ではありません。

7
Abhijit Sarkar

Spring Bootを使用してアップロードサンプルをビルドしていて、同じ問題を解決しています。プロジェクトのルートパスのみを取得したいのですが。 (例:/ sring-boot-upload)

以下のコードが機能することがわかります:

upload.dir.location=${user.dir}\\uploadFolder
6
chendu
your.basedir=${project.basedir}/db/init
spring.datasource.url=jdbc:hsqldb:file:${your.basedir}

@Value("${your.basedir}")
private String file;

new ClassPathResource(file).getURI().toString()
0
membersound