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

标签 java properties spring-boot

我有一个 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 {
    ...
}

最佳答案

您可以使用@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");
    }

}

希望对你有帮助

关于java - 如何使用 Spring Boot 从 java 属性文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38281512/

相关文章:

java - 使用具有不可嵌入依赖项的 Maven 设置集成测试环境

java - ThreadPoolExecutor java 中的 workerCountOf() 方法

java - 无法从 <util :properties> 获取 spring context.getBean()

c++ - 使用类的公共(public)方法设置类的私有(private)属性,C++

mongodb - 使用 Grails 3.0 在数据库中存储 Spring Boot 用户

jsf - 如何将OmniFaces与Spring Boot集成

java - 使用 find() 方法第一个实例不匹配

java - Java 中与 Stack 相关的几个问题

c# - 面向对象 : Using Properties and Constructor

Spring Boot应用程序实际上在端口0上运行,而不是随机运行