小编典典

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

spring-boot

我有一个SpringBoot应用程序,我想从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 {
    ...
}

阅读 405

收藏
2020-05-30

共1个答案

小编典典

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

}

希望这可以帮助

2020-05-30