如何使用 Spring Boot 从 java 属性文件中读取数据

新手上路,请多包涵

我有一个 Spring Boot 应用程序,我想从我的 application.properties 文件中读取一些变量。事实上,下面的代码就是这样做的。但我认为这种替代方法有一个很好的方法。

 Properties prop = new Properties();
InputStream input = null;

try {
    input = new FileInputStream("config.properties");
    prop.load(input);
    gMapReportUrl = prop.getProperty("gMapReportUrl");
} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    ...
}

原文由 Arif Acar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 713
2 个回答

您可以使用 @PropertySource 将您的配置外部化为属性文件。有多种方法可以获取属性:

1. 使用 @ValuePropertySourcesPlaceholderConfigurer 将属性值分配给字段以解决 ${} 中的 @Value

 @Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Value("${gMapReportUrl}")
    private String gMapReportUrl;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

2. 使用 Environment 获取属性值:

 @Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Autowired
    private Environment env;

    public void foo() {
        env.getProperty("gMapReportUrl");
    }

}

希望这可以帮助

原文由 Wilson 发布,翻译遵循 CC BY-SA 3.0 许可协议

我创建了以下课程

配置工具.java

 @Configuration
public class ConfigUtility {

    @Autowired
    private Environment env;

    public String getProperty(String pPropertyKey) {
        return env.getProperty(pPropertyKey);
    }
}

并按如下方式调用以获取 application.properties 值

我的类.java

 @Autowired
private ConfigUtility configUtil;

public AppResponse getDetails() {

  AppResponse response = new AppResponse();
    String email = configUtil.getProperty("emailid");
    return response;
}

应用程序.properties

emailid=sunny@domain.com

单元测试,按预期工作……

原文由 Sunny 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题