【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),参考如下调整。

 

 修正后的打印效果:

 

posted @   飞翔在天  阅读(828)  评论(0编辑  收藏  举报
编辑推荐:
· 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)
点击右上角即可分享
微信分享提示