Spring中读取配置文件的五种方式
warning:
这篇文章距离上次修改已过432天,其中的内容可能已经有所变动。
Spring框架提供了多种方式来读取配置文件,以下是五种常见的方式:
- 使用
@Value注解
@Value("${some.property}")
private String property;- 使用
Environment接口
@Autowired
private Environment env;
public void someMethod() {
String property = env.getProperty("some.property");
}- 使用
@PropertySource和PropertiesFactoryBean
@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
Properties properties = new Properties();
// 这里可以加载额外的properties文件
try {
properties.load(new FileInputStream("classpath:config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
pspc.setProperties(properties);
return pspc;
}
}- 使用
ConfigurationProperties
@ConfigurationProperties(prefix = "some")
public class ConfigProperties {
private String property;
// getters and setters
}然后在配置类上使用@EnableConfigurationProperties(ConfigProperties.class)注解。
- 使用
@ConfigurationProperties和@PropertySource
@Configuration
@PropertySource("classpath:config.properties")
@EnableConfigurationProperties(ConfigProperties.class)
public class AppConfig {
// ...
}以上五种方式可以根据实际需求选择使用,Spring Boot中推荐使用@ConfigurationProperties。
评论已关闭