网站首页 > 博客文章 正文
简介
本文我们将会讨怎么在Spring Boot中使用Properties。使用Properties有两种方式,一种是java代码的注解,一种是xml文件的配置。本文将会主要关注java代码的注解。
使用注解注册一个Properties文件
注册Properties文件我们可以使用@PropertySource 注解,该注解需要配合@Configuration 一起使用。
@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
//...
}
我们也可以使用placeholder来动态选择属性文件:
@PropertySource({
"classpath:persistence-${envTarget:mysql}.properties"
})
@PropertySource也可以多次使用来定义多个属性文件:
@PropertySource("classpath:foo.properties")
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfig {
//...
}
我们也可以使用@PropertySources来包含多个@PropertySource:
@PropertySources({
@PropertySource("classpath:foo.properties"),
@PropertySource("classpath:bar.properties")
})
public class PropertiesWithJavaConfig {
//...
}
使用属性文件
最简单直接的使用办法就是使用@Value注解:
@Value( "${jdbc.url}" )
private String jdbcUrl;
我们也可以给属性添加默认值:
@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;
如果要在代码中使用属性值,我们可以从Environment API中获取:
@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));
Spring Boot中的属性文件
默认情况下Spring Boot 会读取application.properties文件作为默认的属性文件。当然,我们也可以在命令行提供一个不同的属性文件:
java -jar app.jar --spring.config.location=classpath:/another-location.properties
如果是在测试环境中,我们可以使用@TestPropertySource 来指定测试的属性文件:
@RunWith(SpringRunner.class)
@TestPropertySource("/foo.properties")
public class FilePropertyInjectionUnitTest {
@Value("${foo}")
private String foo;
@Test
public void whenFilePropertyProvided_thenProperlyInjected() {
assertThat(foo).isEqualTo("bar");
}
}
除了属性文件,我们也可以直接以key=value的形式:
@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"foo=bar"})
public class PropertyInjectionUnitTest {
@Value("${foo}")
private String foo;
@Test
public void whenPropertyProvided_thenProperlyInjected() {
assertThat(foo).isEqualTo("bar");
}
}
使用@SpringBootTest,我们也可以使用类似的功能:
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class)
public class SpringBootPropertyInjectionIntegrationTest {
@Value("${foo}")
private String foo;
@Test
public void whenSpringBootPropertyProvided_thenProperlyInjected() {
assertThat(foo).isEqualTo("bar");
}
}
@ConfigurationProperties
如果我们有一组属性,想将这些属性封装成一个bean,则可以考虑使用@ConfigurationProperties。
@ConfigurationProperties(prefix = "database")
public class Database {
String url;
String username;
String password;
// standard getters and setters
}
属性文件如下:
database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar
Spring Boot将会自动将这些属性文件映射成java bean的属性,我们需要做的就是定义好prefix。
yaml文件
Spring Boot也支持yaml形式的文件,yaml对于层级属性来说更加友好和方便,我们可以看下properties文件和yaml文件的对比:
database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar
secret: foo
database:
url: jdbc:postgresql:/localhost:5432/instance
username: foo
password: bar
secret: foo
注意yaml文件不能用在@PropertySource中。如果你使用@PropertySource,则必须指定properties文件。
Properties环境变量
我们可以这样传入property环境变量:
java -jar app.jar --property="value"
shell
java -Dproperty.name=”value” -jar app.jar
或者这样:
~~~shell
export name=value
java -jar app.jar
环境变量有什么用呢? 当指定了特定的环境变量时候,Spring Boot会自动去加载application-environment.properties文件,Spring Boot默认的属性文件也会被加载,只不过优先级比较低。
java代码配置
除了注解和默认的属性文件,java也可以使用PropertySourcesPlaceholderConfigurer来在代码中显示加载:
@Bean
public static PropertySourcesPlaceholderConfigurer properties(){
PropertySourcesPlaceholderConfigurer pspc
= new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[ ]
{ new ClassPathResource( "foo.properties" ) };
pspc.setLocations( resources );
pspc.setIgnoreUnresolvablePlaceholders( true );
return pspc;
}
欢迎关注我的公众号:程序那些事,更多精彩等着您!
更多内容请访问:flydean的博客 flydean.com
猜你喜欢
- 2024-09-26 基于 redis 和 ehcache 的两级缓存组件 uncode-cache
- 2024-09-26 melon-idfactory主键工厂,提供ID生成服务,保证ID的唯一性。
- 2024-09-26 Spring-基础笔记(一)(spring详细教程)
- 2024-09-26 带你读源码2——Spring源码分析之容器的刷新 - refresh()
- 2024-09-26 super-diamond 结合springboot的使用经验(用过的都说好)
- 2024-09-26 还在为数据同步而苦恼吗?手把手教你实现canal数据同步(一)
- 2024-09-26 源码分析:Spring是如何获取容器中的Bean?
- 2024-09-26 五种方式让你在java中读取properties文件内容
- 2024-09-26 图表显示日志离线信息(图表显示日志离线信息什么意思)
- 2024-09-26 Java程序员 必须掌握的 20+ 种 Spring 常用注解
你 发表评论:
欢迎- 最近发表
-
- 给3D Slicer添加Python第三方插件库
- Python自动化——pytest常用插件详解
- Pycharm下安装MicroPython Tools插件(ESP32开发板)
- IntelliJ IDEA 2025.1.3 发布(idea 2020)
- IDEA+Continue插件+DeepSeek:开发者效率飙升的「三体组合」!
- Cursor:提升Python开发效率的必备IDE及插件安装指南
- 日本旅行时想借厕所、买香烟怎么办?便利商店里能解决大问题!
- 11天!日本史上最长黄金周来了!旅游万金句总结!
- 北川景子&DAIGO缘定1.11 召开记者会宣布结婚
- PIKO‘PPAP’ 洗脑歌登上美国告示牌
- 标签列表
-
- ifneq (61)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)