返回

Spring Boot 中如何从外部路径访问 app.properties

java

在 Spring Boot 中从外部路径访问 app.properties

简介

在 Spring Boot 应用程序中,通常从类路径访问 app.properties 文件。但是,有时候我们需要从类路径以外的外部路径,例如 URL 或其他目录,访问 app.properties 文件。本文将指导你如何实现这一操作。

创建 RemotePropertySource

首先,需要创建一个 RemotePropertySource bean。该 bean 负责从外部路径加载 app.properties 文件。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.RemotePropertySourceFactory;

@Configuration
public class AppPropertiesConfig {

    private static final String PROPERTIES_URL = "https://drive.google.com/file/d/1vdB2hpm6DRVsCimFddoq9P5mOh-ibeod/view?usp=sharing";

    @Bean
    public RemotePropertySource remotePropertySource() {
        return new RemotePropertySourceFactory().createPropertySource("remotePropertySource", PROPERTIES_URL);
    }
}

注册 RemotePropertySource

接下来,需要将 RemotePropertySource 注册到 Spring 容器中。可以使用 @Bean 注解来实现。

使用 app.properties 中的属性

注册 RemotePropertySource 后,就可以像访问其他属性源一样访问 app.properties 中的属性。

示例代码

以下是一个访问外部 app.properties 文件的完整示例代码:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.RemotePropertySourceFactory;

@Configuration
public class AppPropertiesConfig {

    private static final String PROPERTIES_URL = "https://drive.google.com/file/d/1vdB2hpm6DRVsCimFddoq9P5mOh-ibeod/view?usp=sharing";

    @Bean
    public RemotePropertySource remotePropertySource() {
        return new RemotePropertySourceFactory().createPropertySource("remotePropertySource", PROPERTIES_URL);
    }

    @Value("${my.property}")
    private String myProperty;

    public String getMyProperty() {
        return myProperty;
    }
}

常见问题解答

  • 如何指定 app.properties 文件的 URL?

    • PROPERTIES_URL 常量中指定 URL。
  • 需要公开 app.properties 文件吗?

    • 是的,需要确保 app.properties 文件已在指定的 URL 上公开。
  • 如何处理加载异常?

    • 可以使用 @EventListener(RemoteApplicationEvent.class) 注解监听远程属性源加载事件,并在发生异常时采取适当的措施。
  • RemotePropertySource 仅支持 HTTP URL 吗?

    • 不,它还支持其他协议,例如 FTP 和 SFTP。
  • 如何访问加载的属性?

    • 可以使用 @Value 注解或 Environment 类访问已加载的属性。