【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 @ 2019-12-07 13:27  飞翔在天  阅读(811)  评论(0编辑  收藏  举报