Spring Boot 配置绑定

Spring Boot 配置绑定

配置绑定就是将配置文件参数和JavaBean中的属性绑定起来,比如:

  • 数据库连接信息
  • redis配置信息
  • rabbitMq中间件信息

Spring Boot 提供两种配置绑定方式:

  • 使用@ConfigurationProperties
  • 使用@Value

@Value

当我们需要为若干个属性添加配置时,我们可以使用@Value

  1. 在application.properties添加配置参数
book.name=钢铁是怎么练成的
book.price=100
book.publisher=文艺出版社
  1. 添加普通类,并添加@Component注解
package com.ibm.cn.config;

import org.springframework.stereotype.Component;

/**
 * @author 苏格拉没有底
 * @version 1.0
 * @DATE 2021/9/10 10:09
 */
@SuppressWarnings("all")
@Component
public class Book {
    private String name ;

    private Long price ;

    private String publisher ;

	// getter , setter , toString ...
}


  1. 在需要绑定的属性上添加@Value注解
    @Value("${book.name}")
    private String name ;

    @Value("${book.price}")
    private Long price ;

    @Value("${book.publisher}")
    private String publisher ;
  1. 编写测试类
    @Autowired
    Book book ;

    @Test
    void testBook(){
        System.out.println(book);
    }
  1. 查看结果:

image-20210910101438493

@ConfigurationProperties

当需要绑定的属性较少时, 我们可以使用@Value ; 当需要绑定的属性较多时 , 我们使用@ConfigurationProperties

  1. 添加配置文件bookConfig.properties
book.name=钢铁是怎么练成的
book.price=100
book.publisher=文艺出版社
  1. 添加配置类

注意:一定要添加PropertySource注解,并指定配置文件名称以及编码类型, 否则可能会产生中文乱码

package com.ibm.cn.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @author 苏格拉没有底
 * @version 1.0
 * @DATE 2021/9/10 9:23
 */
@SuppressWarnings("all")
@Component
@ConfigurationProperties(prefix="book")
@PropertySource(value = {"classpath:bookConfig.properties"} ,encoding = "utf-8")
public class TestBookConfig {

    private String name ;

    private Long price ;

    private String publisher ;

    // getter , setter , toString ...
}


  1. 编写测试类
    @Autowired
    TestBookConfig testBookConfig ;

    @Test
    void testConfig(){
        System.out.println(testBookConfig);
    }
  1. 查看结果

image-20210910100418651

  1. 总结
    1. 配置类要加上@ConfigurationProperties, 并指定属性prefix为配置文件中的前缀
    2. 配置类@PropertySource,并指定配置文件名称以及编码类型, 否则可能会产生中文乱码
    3. 配置类一定要加上@Component, 需要将该配置加载到容器中才能被使用
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值