• SpringBoot 属性配置文件数据注入配置和yml与properties区别


    前言

    我们知道SpringBoot 通过配置类来解放一堆的xml文件配置,通属性配置文件,来进行,系统全局属性配置,这样极大的简化了我们开发过程,java web 也可以甜甜的从此

    快速配置

    Spring Boot默认加载支持 application.properties、application.yaml和application*.yml三种拓展名结尾的全局属性配置文件处理

    它们顺序优先级为: application*.properties>application*.yaml>application*.yml

    即在application.properties或application.yml等文件中添加属性配置

    可以使用@Value注解将属性值注入到beans中,或使用@ConfigurationProperties注解将属性值绑定到结构化的beans中

    @Value是Spring框架提供的注解,用来读取配置文件中的属性并逐个注入到Bean对象对应的属性中,Spring Boot框架对Spring框架的@Value注解进行了默认继承

    1. resources文件下新增application.properties文件,配置对应的属性
    student.name=kenx
    student.age=23
    
    1. 新增java bean 把对应的属性注入到java bean中对应字段使用@Value注解将属性值注入到对应属性上。
    @Component
    @Data
    public class User {
        @Value("${student.name}")
        private String name;
        @Value("${student.age}")
        private Integer age;
    }
    

    @Component 添加到spring ioc容器中,@Data 添加getter,setter

    1. 写用例测试
    @SpringBootTest(
            webEnvironment = SpringBootTest.WebEnvironment.NONE,
            classes = cn.soboys.kmall.api.ApiApplication.class)
    public class PropertiesTest {
    
        @Autowired
        private User properties;
    
        @Test
        public void a(){
            String a= String.format( "student name  is %s student age is %s",properties.getName(),properties.getAge());
            System.out.println(a);
        }
    }
    

    我看可以看到控制台正常打印,数据注入成功

    2021-09-08 10:53:02 INFO  background-preinit org.hibernate.validator.internal.util.Version HV000001: Hibernate Validator 6.1.7.Final
    2021-09-08 10:53:02 INFO  main PropertiesTest Starting PropertiesTest using Java 1.8.0_202 on xiangyongdeMacBook-Pro.local with PID 45463 (started by xiangyong in /Users/xiangyong/selfProject/project/kmall/kmall-api)
    2021-09-08 10:53:02 INFO  main PropertiesTest The following profiles are active: test,mptest
     _ _   |_  _ _|_. ___ _ |    _ 
    | | |/|_)(_| | |_  |_)||_|_ 
         /               |         
                            3.4.1 
    2021-09-08 10:53:08 INFO  main PropertiesTest Started PropertiesTest in 6.132 seconds (JVM running for 7.783)
    
    student name  is kenx student age is 23
    
    1. @ConfigurationProperties注解将属性值绑定到结构化的beans

    上面通过@Value一个·一个注入很不方便

    @Component
    @Data
    @ConfigurationProperties(prefix = "student")
    public class User {
        private String name;
        private Integer age;
    }
    

    这样极大简化代码,对于属性比较多,结构化bean,很有必要可以通过@ConfigurationProperties(prefix = "student")这种方式指定前缀

    当然有时候我们需要自定义加载属性配置文件 使用@PropertySource加载配置文件

    test.id=100
    test.name=lucy
    
    
    package com.lzx.springboot01demo.pojo;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    @Configuration		// 自定义配置类
    @PropertySource("classpath:test.properties") 	// 指定自定义配置文件位置和名称
    @EnableConfigurationProperties(MyProperties.class)		// 开启对应配置类的属性注入功能
    @ConfigurationProperties(prefix = "test")		// 指定配置文件注入属性前缀
    public class MyProperties {
    
        private Integer id;
        private String name;
    
        // 省略getter/setter方法
        // 省略toString()方法
    }
    
    

    1. @Configuration注解表示当前类是一个自定义配置类,并添加为Spring容器的组件,也可使用传统的@Component注解

    1. @PropertySource("classpath:test.properties")指定自定义配置文件位置和名称

    2. @ConfigurationProperties(prefix = "test")指定将配置文件中前缀为test的属性注入到配置类的属性中

    3. @EnableConfigurationProperties(MyProperties.class)表示开启对应配置类的属性注入功能,如果配置类上使用的是@Component注解而非@Configuration,@EnableConfigurationProperties(MyProperties.class)注解可以省略

    application.properties配置文件

    #配置数字
    person.id=1
    #配置字符串
    person.name=tom
    #配置List集合
    person.hoby=吃饭,睡觉,打豆豆
    #配置String[]数组
    person.family=father,mother
    #配置map集合
    person.map.k1=v1
    person.map.k2=v2
    #配置对象type属性
    person.pet.type=dog
    #配置对象name属性
    person.pet.name=旺财
    

    application.y(a)ml配置文件

    1. value值为普通数据类型(例如:数字、字符串、布尔)
    server:
      port: 8081
      path: /hello
    
    
    1. value值为数组或单列集合

    主要有两种写法:缩进式写法和行内式写法;其中缩进式写法又有两种写法:

    缩进式写法1

    person:
      hobby:
        - play
        - read
        - sleep
    

    缩进式写法2

    person:
      hobby:
        play,
        read,
        sleep
    
    

    行内式写法:

    person:
      hobby: [play,read,sleep]
    
    
    1. value值为Map或对象

    缩进式写法

    person:
      map:
        k1: v1
        k2: v2
    
    

    行内式写法:

    person:
      map: {k1: v1, k2: v2}
    
    

    注意 使用Spring Boot全局配置文件设置属性时,

    如果配置的属性是已有属性,例如服务端口server.port,那么Spring Boot会扫描并读取这些配置属性,覆盖已有的默认配置;
    如果配置的是自定义属性,则还需要在程序中注入这些配置属性方可生效

    默认属性和参数引用

    SpringBoot属性配置文件中默认给我们提供了一些特有的全局属性参数值我们可以直接获取

    使用Spring Boot内嵌的RandomValuePropertySource类进行随机值注入。

    # 配置随机值
    my.secret=${random.value}
    # 配置随机整数
    my.number=${random.int}
    # 配置随机long类型的整数
    my.bigbumber=${random.long}
    # 配置uuid
    my.uuid=${random.uuid}
    # 配置小于10的整数
    my.number.less.than.ten=${random.int(10)}
    # 配置范围在[1024,65536]的随机整数
    my.number.in.range=${random.int[1024,65536]}
    

    当然我们也可以自定义引用自己定义的值

    # 参数间引用
    app.name=MyApp
    app.description=${app.name} is a Spring Boot application
    
    
  • 相关阅读:
    『Python』进程同步
    『Python』多进程
    『GoLang』协程与通道
    『GoLang』错误处理
    『码农翻身』语言的学习
    『GoLang』fmt包的使用
    异或运算符(^)、与运算符(&)、或运算符(|)、反运算符(~)、右移运算符(>>)、无符号右移运算符(>>>)
    HTML DOM focus() 方法
    JavaScript中的indexOf使用方法
    HTML 5 中的textarea标签
  • 原文地址:https://www.cnblogs.com/kenx/p/15242944.html
Copyright © 2020-2023  润新知