在Spring 和 Spring Boot中使用配置属性
一、在spring中使用配置属性
1.1 手动指定配置文件
在spring 中使用@PropertySource注释选择属性文件,可以选择多个。
@Configuration
@PropertySource("classpath:foo.properties")
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfig {
//...
}
// 动态选择
@PropertySource({
"classpath:persistence-${envTarget:mysql}.properties"
})
...
1.2 获取属性值
// 使用@Value注入
@Value( "${jdbc.url}" )
private String jdbcUrl;
// 使用@Value注入,带默认值
@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;
// 使用Environment API获取
@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"))