我有一个 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。
通过使用 @Value
和 PropertySourcesPlaceholderConfigurer
将属性值分配给字段以解析 @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/