Spring Boot配置绑定

系列文章目录

所谓“配置绑定”就是把配置文件中的值与 JavaBean 中对应的属性进行绑定。
通常,我们会把一些配置信息(例如,数据库配置)放在配置文件中,然后通过 Java 代码去读取该配置文件,并且把配置文件中指定的配置封装到 JavaBean(实体类) 中。


SpringBoot 提供了以下 2 种方式进行配置绑定:

  • 使用 @ConfigurationProperties 注解
  • 使用 @Value 注解


前言

所谓“配置绑定”就是把配置文件中的值与 JavaBean 中对应的属性进行绑定。
通常,我们会把一些配置信息(例如,数据库配置)放在配置文件中,然后通过 Java 代码去读取该配置文件,并且把配置文件中指定的配置封装到 JavaBean(实体类) 中。


一、@ConfigurationProperties?

通过 Spring Boot 提供的 @ConfigurationProperties 注解,可以将全局配置文件中的配置数据绑定到 JavaBean 中。

下面我们以 Spring Boot 项目 helloworld 为例,演示如何通过 @ConfigurationProperties 注解进行配置绑定。

  1. 在 helloworld 的全局配置文件 appilcation.yml 中添加以下自定义属性。
person:
  lastName: 张三
  age: 18
  boss: false
  birth: 1990/12/12
  maps: { k1: v1,k2: 12 }
  lists:
    ‐ lisi
    ‐ zhaoliu
  dog:
    name: 迪迪
    age: 5
  1. 在 helloworld 项目的 com.dhcc.itsm.bean 中创建一个名为 Person 的实体类,并将配置文件中的属性映射到这个实体类上,代码如下。
package com.dhcc.itsm.bean;

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

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
*
* @ConfigurationProperties:告诉 SpringBoot 将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能;
*/
@Component
@ConfigurationProperties(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 Person() {
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getBoss() {
        return boss;
    }

    public void setBoss(Boolean boss) {
        this.boss = boss;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public List<Object> getLists() {
        return lists;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Person(String lastName, Integer age, Boolean boss, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.lastName = lastName;
        this.age = age;
        this.boss = boss;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }

    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}

注意:
只有在容器中的组件,才会拥有 SpringBoot 提供的强大功能。如果我们想要使用 @ConfigurationProperties 注解进行配置绑定,那么首先就要保证该对 JavaBean 对象在 IoC 容器中,所以需要用到 @Component 注解来添加组件到容器中。
JavaBean 上使用了注解 @ConfigurationProperties(prefix = “person”) ,它表示将这个 JavaBean 中的所有属性与配置文件中以“person”为前缀的配置进行绑定。

package com.dhcc.itsm.bean;

public class Dog {
    private String name;
    private String age;

    public Dog() {
    }

    public Dog(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public String getAge() {
        return age;
    }
}
  1. 修改 HelloController 的代码,在浏览器中展示配置文件中各个属性值,代码如下。

import net.biancheng.www.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {
    @Autowired
    private Person person;

    @ResponseBody
    @RequestMapping("/hello")
    public Person hello() {
        return person;
    }
}
  1. 重启项目,使用浏览器访问 “http://localhost:8081/hello”,结果如下图。

@Value

当我们只需要读取配置文件中的某一个配置时,可以通过 @Value 注解获取。:

  1. 以 Spring Boot 项目 helloworld 为例,修改实体类 Person 中的代码,使用 @Value 注解进行配置绑定,代码如下。
package net.biancheng.www.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class Person {
    @Value("${person.lastName}")
    private String lastName;
    @Value("${person.age}")
    private Integer age;
    @Value("${person.boss}")
    private Boolean boss;
    @Value("${person.birth}")
    private Date birth;

    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;

    public Person() {

    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getBoss() {
        return boss;
    }

    public void setBoss(Boolean boss) {
        this.boss = boss;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public List<Object> getLists() {
        return lists;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Person(String lastName, Integer age, Boolean boss, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.lastName = lastName;
        this.age = age;
        this.boss = boss;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }

    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}

重启项目,使用浏览器访问 “http://localhost:8081/hello”,结果如下图。


在这里插入图片描述

@Value 与 @ConfigurationProperties 对比

@Value 和 @ConfigurationProperties 注解都能读取配置文件中的属性值并绑定到 JavaBean 中,但两者存在以下不同。

  • 使用位置不同
  • @ConfigurationProperties:标注在 JavaBean 的类名上;
  • @Value:标注在 JavaBean 的属性上。
    -功能不同
  • @ConfigurationProperties:用于批量绑定配置文件中的配置;
  • @Value:只能一个一个的指定需要绑定的配置。
  • 松散绑定支持不同
    @ConfigurationProperties:支持松散绑定(松散语法),例如实体类 Person 中有一个属性为 lastName,那么配置文件中的属性名支持以下写法:
  • person.firstName
  • person.first-name
  • person.first_name
  • PERSON_FIRST_NAME

@Vaule:不支持松散绑定。

  • SpEL 支持不同
  • @ConfigurationProperties:不支持 SpEL 表达式;
  • @Value:支持 SpEL 表达式。
    5、 复杂类型封装
  • @ConfigurationProperties:支持所有类型数据的封装,例如 Map、List、Set、以及对象等;
  • @Value:只支持基本数据类型的封装,例如字符串、布尔值、整数等类型。
    6、 应用场景不同
    @Value 和 @ConfigurationProperties 两个注解之间,并没有明显的优劣之分,它们只是适合的应用场景不同而已。
  • 若只是获取配置文件中的某项值,则推荐使用 @Value 注解;
  • 若专门编写了一个 JavaBean 来和配置文件进行映射,则建议使用 @ConfigurationProperties 注解。

我们在选用时,根据实际应用场景选择合适的注解能达到事半功倍的效果。

@PropertySource

如果将所有的配置都集中到 application.properties 或 application.yml 中,那么这个配置文件会十分的臃肿且难以维护,因此我们通常会将与 Spring Boot 无关的配置(例如自定义配置)提取出来,写在一个单独的配置文件中,并在对应的 JavaBean 上使用 @PropertySource 注解指向该配置文件。

  1. 以 helloworld 为例,将与 person 相关的自定义配置移动到 src/main/resources 下的 person.properties 中(注意,必须把 application.properties 或 application.yml 中的相关配置删除),如下图。
    在这里插入图片描述
    person.properties 的配置如下。
person.last-name=李四
person.age=12
person.birth=2000/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=2
  1. 在 Person 使用 @PropertySource 注解指向 person.properties,代码如下。
package net.biancheng.www.bean;

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

import java.util.Date;
import java.util.List;
import java.util.Map;

@PropertySource(value = "classpath:person.properties")//指向对应的配置文件
@Component
@ConfigurationProperties(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 Person() {

    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getBoss() {
        return boss;
    }

    public void setBoss(Boolean boss) {
        this.boss = boss;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public List<Object> getLists() {
        return lists;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Person(String lastName, Integer age, Boolean boss, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.lastName = lastName;
        this.age = age;
        this.boss = boss;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }

    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}
  1. 重启项目,使用浏览器访问 “http://localhost:8081/hello”,结果如下图。
    4.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Spring Boot的动态配置指的是在运行时对应用程序的配置进行修改或更新,而不需要重新启动应用程序。 在面试中,可能会涉及到Spring Boot动态配置的原理、作用以及相关的实现方法。 首先,Spring Boot动态配置的原理是基于Spring框架的属性注入和监听机制。Spring Boot应用程序的配置是通过`application.properties`或`application.yml`文件进行管理的。当应用程序启动时,Spring Boot会读取这些配置文件中的属性值并注入到Spring Bean中,从而实现配置的逻辑。 而动态配置则是通过监听属性值的变化来实现的。Spring Boot提供了`@ConfigurationProperties`注解和`@Value`注解两种常用的配置注入方式。可以通过在配置类中使用`@ConfigurationProperties`注解,将需要动态修改的属性注入到Bean中。然后,通过添加一个监听器,监听属性值的变化,一旦属性值发生改变,就会触发监听事件并重新加载配置。 有多种方法可以实现Spring Boot的动态配置。一种常用的方法是使用Spring Cloud Config服务来集中管理和存储配置,并通过消息总线发送配置变更的通知。另一种方法是使用Spring Cloud Bus,它使用消息代理将配置的变更通知传播给多个实例。 还可以使用第三方的配置中心,如Apache Zookeeper、Consul等来进行动态配置。这些配置中心提供了API来更新和获取配置信息,并且支持监听配置变化的功能。 总之,Spring Boot的动态配置是为了方便应用程序的配置管理和更新,使应用程序在运行时可以灵活地适应不同的配置需求。 ### 回答2: Spring Boot的动态配置是指在应用程序运行时可以根据需要动态更改配置参数,而无需重启应用程序。这种灵活性使得应用程序能够根据环境的变化或者特定的用户需求进行调整和优化。 在Spring Boot中,我们可以通过使用Spring Cloud Config等工具或者自定义实现来实现动态配置Spring Cloud Config是Spring Cloud的一个子项目,它提供了一个集中式的配置管理服务,允许将应用程序的配置文件存储在远程仓库中(如Git或SVN),并在运行时动态地从这些仓库中获取配置。 使用Spring Cloud Config,我们可以将应用程序的配置信息集中管理,而不需要将配置参数硬编码到代码中。通过轮询或者推送的方式,应用程序可以定时或者实时获取最新的配置信息。这样,我们可以在不重新部署应用程序的情况下,更改配置参数,从而使得应用程序可以快速适应环境的变化或者满足特定的需求。 动态配置的好处包括: 1. 避免了重新部署应用程序的麻烦和风险,提高了开发和部署效率。 2. 使得应用程序可以根据不同环境的需要进行配置,达到最佳性能和适应性。 3. 实现了配置信息的集中管理,方便追踪和管理配置变更的历史记录。 但是,动态配置也需要考虑安全性和稳定性的问题。配置信息的修改和获取需要进行权限控制,以防止非法操作。另外,动态配置可能会对应用程序的稳定性造成一定影响,因此在配置更新过程中需要考虑到应用程序可能的异常处理和兼容性。 总之,Spring Boot的动态配置为应用程序提供了更大的灵活性和可维护性,使得应用程序在运行时可以根据需要动态调整参数,从而达到更好的性能和适应性。 ### 回答3: Spring Boot的动态配置是指在程序运行时可以根据需要动态更改配置信息的功能。它通过提供一种灵活的配置机制,使得应用程序的配置可以在不重启应用的情况下进行修改和更新。 在Spring Boot中,可以通过使用@ConfigurationProperties注解来定义配置类,将配置信息映射到该类的属性上。通过@ConfigurationProperties注解,我们可以将外部配置文件中的属性值绑定配置类的属性上。当配置文件中的属性值发生改变时,Spring Boot会自动更新配置类中对应的属性值。 动态配置的优点是可以在应用程序运行时实时修改配置信息,而不需要重启应用程序。这样可以提高应用程序的可扩展性和可维护性。例如,在一个具有高流量访问的网站中,如果需要增加线程池的大小来提高并发处理能力,可以通过修改配置文件中的线程池大小属性来达到目的,而不需要停止应用程序。 在Spring Boot中,可以使用Spring Cloud Config来实现动态配置Spring Cloud Config提供了一种集中化的外部配置管理方案,可以将配置文件存储在Git、SVN或本地文件系统等地方,应用程序可以通过访问配置服务器来获取最新的配置信息。通过Spring Cloud Config,我们可以在运行时修改配置文件,并使得配置信息对应用程序立即生效,实现了动态配置的功能。 总而言之,Spring Boot的动态配置是指在程序运行时可以实时修改配置信息的功能。它通过使用@ConfigurationProperties注解和Spring Cloud Config等机制来实现,提供了一种灵活且方便的方式来管理和更新应用程序的配置信息。这种能力提高了应用程序的可扩展性和可维护性,使得应用程序能够更加灵活地适应不同的环境和需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

缘来在

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值