如何使用 Spring Boot 从 java 属性文件中读取数据 [英] How to read data from java properties file using Spring Boot
问题描述
我有一个 Spring Boot 应用程序,我想从我的 application.properties
文件中读取一些变量.事实上,下面的代码就是这样做的.但我认为这个替代方案有一个很好的方法.
I have a spring boot application and I want to read some variable from my application.properties
file. In fact below codes do that. But I think there is a good method for this alternative.
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
将您的配置具体化到一个属性文件中.有多种获取属性的方法:
You can use @PropertySource
to externalize your configuration to a properties file. There is number of way to do get properties:
1.通过使用 @Value
和 PropertySourcesPlaceholderConfigurer
将属性值分配给字段以解析 @Value
中的 ${}
:
1.
Assign the property values to fields by using @Value
with PropertySourcesPlaceholderConfigurer
to resolve ${}
in @Value
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Value("${gMapReportUrl}")
private String gMapReportUrl;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2.使用 Environment
获取属性值:
2.
Get the property values by using Environment
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void foo() {
env.getProperty("gMapReportUrl");
}
}
希望能帮到你
这篇关于如何使用 Spring Boot 从 java 属性文件中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!