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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 项目中,读取 YAML 配置文件的方式与读取 properties 配置文件的方式类似。可以使用 `@ConfigurationProperties` 注解将配置文件中的属性Java 对象绑定起来,也可以使用 `@Value` 注解逐个读取配置。 以下是使用 `@ConfigurationProperties` 注解读取 YAML 配置文件的示例代码: 1. 创建一个 Java 类,用于存储 YAML 配置文件中的属性: ```java @ConfigurationProperties(prefix = "example") public class ExampleProperties { private String name; private int age; //其他属性... //getter和setter方法... } ``` 2. 在 YAML 配置文件中定义属性: ```yaml example: name: "Tom" age: 18 #其他属性... ``` 3. 在 Spring Boot 应用程序的配置类中,启用 `@EnableConfigurationProperties` 注解,并将 `ExampleProperties` 类加入到 Spring 容器中: ```java @EnableConfigurationProperties(ExampleProperties.class) @Configuration public class AppConfig { @Bean public ExampleProperties exampleProperties() { return new ExampleProperties(); } } ``` 4. 在需要读取配置的地方,注入 `ExampleProperties` 对象即可使用: ```java @RestController public class ExampleController { @Autowired private ExampleProperties exampleProperties; @GetMapping("/example") public ExampleProperties getExample() { return exampleProperties; } } ``` 以上示例代码使用了 `@ConfigurationProperties` 注解将 YAML 配置文件中的属性与 `ExampleProperties` 类绑定起来,并在 Spring Boot 应用程序的配置类中将 `ExampleProperties` 类加入到 Spring 容器中。在需要读取配置的地方,使用 `@Autowired` 注解注入 `ExampleProperties` 对象即可使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值