【Spring&SpringBoot】读取变量的N种方式
参考:
SpringBoot读取配置的6种方式 https://www.bilibili.com/video/BV1hh4y1j7mC/?spm_id_from=333.337.search-card.all.click&vd_source=898d5514be58985430a49b46d5500c13
尚硅谷SpringBoot视频 P10~P13
基于Spring读取配置:
1、逐个配置:@Value:支持SpEL语法,不支持JSR303校验;不支持复杂类型注解(如map)
2、指定配置文件 @PropertySource("classpath:foo.properties") + @Configuration annotation: // 指定多个
基于Spring Boot读取配置
1、默认读取:src/main/resources/application.properties 或 application.yaml
2、定义环境相关参数 application-environment.properties
3、简化配置:@ConfigurationPeroperties(prefix=""), 批量注入文件中属性,不支持SpEL语法,JSR303校验
4、指定测试专用properties 文件:src/test/resources/
5、注解:@TestPropertySource
@RunWith(SpringRunner.class) @TestPropertySource("/foo.properties") public class FilePropertyInjectionUnitTest { @Value("${foo}") private String foo; @Test public void whenFilePropertyProvided_thenProperlyInjected() { assertThat(foo).isEqualTo("bar"); } }
配置随机值:If we don't want determinist property values, we can use RandomValuePropertySource to randomize the values of properties:
random.number=${random.int} random.long=${random.long} random.uuid=${random.uuid}
其他(不推荐)
PropertySourcesPlaceholderConfigurer :gives us full control over the configuration, with the downside of being more verbose and most of the time, unnecessary.
@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; }
Spring场景:Register a Properties File via Annotations
@Configuration @PropertySource("classpath:foo.properties") public class PropertiesWithJavaConfig { //... }
定义多个
@PropertySource("classpath:foo.properties") @PropertySource("classpath:bar.properties") public class PropertiesWithJavaConfig { //... }
或
@PropertySources({ @PropertySource("classpath:foo.properties"), @PropertySource("classpath:bar.properties") }) public class PropertiesWithJavaConfig { //... }
Spring:注入参数 @Value
补充:取不到值:设置默认值,@Value("${Person.address:CCC}")
Validate JSR 303的使用:会提示lastName格式报错
参数类型不匹配,启动报错
SpringBoot:@ConfigurationPeroperties(prefix="")
application.yaml配置如下:
1 person: 2 lastName: hello 3 age: 18 4 boss: false 5 birth: 2017/12/12 6 maps:{k1: v1, k2: 12} 7 lists: 8 - lisi 9 - zhaoliu 10 dog: 11 name: 小狗 12 age: 12
代码
/** * 将配置文件中配置的每个属性的值,映射到这个组件中 * @ConfigurationProperties 告诉 SpringBoot将本类中所有属性和配置文件中相关配置绑定 * prefix = "person" 配置文件中哪个下面的所有属性一一映射 */ @Component @ConfigurationPeroperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String ,Object> maps; private List<Object> lists; private Dog dog; .... } public class Dog{ private String name; private Integer age; }
Pom.xml增加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!-- Spring Test 插件--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
配置spring test类,验证效果
使用application.properties(先将原有yaml文件中使用#注释,可直接用快捷键 Ctrl+/实现快速屏蔽)
Person.last-name=lisi Person.age=18 Person.boss=false Person.birth=2019/12/12 Person.maps.k1=v1 Person.maps.k2=14 Person.lists=a,b,c
重新Test执行效果:
说明:如果配置文件中配置中文打印乱码,则是工程字符集问题(Properties文件模式GBK编码,需调整UTF-8),参考如下调整。
修正后的打印效果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)