Spring Boot中的Binder类

介绍

Spring Boot中的Binder类是一个用于绑定属性的工具类。它可以将配置文件中的属性值绑定到Java对象中,从而方便地进行配置管理。

简单示例

java 复制代码
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;

@Data
public class MyConfig {
    private String name;
    private int age;

    public MyConfig(Environment environment) {
        Binder binder = Binder.get(environment);
        this.name = binder.bind("myconfig.name", String.class).orElse("lucifer");
        this.age = binder.bind("myconfig.age", Integer.class).orElse(25);
    }
}

使用Binder类将配置文件中的属性值绑定到这些属性中。在构造函数中,首先获取了一个Binder实例,然后使用bind方法将配置文件中的属性值绑定到Java对象中。如果属性不存在,则使用默认值。

配置文件中属性:

java 复制代码
myconfig.name=John
myconfig.age=25

需要将Environment对象传递给MyConfig的构造函数,以便Binder类可以访问配置文件中的属性值。在Spring Boot应用程序中,可以通过@Autowired注解将Environment对象注入到MyConfig类中。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class AppConfig {
    @Autowired
    private Environment environment;

    public MyConfig myConfig() {
        return new MyConfig(environment);
    }
}

常用方法

  • bind方法:将配置文件中的属性值绑定到Java对象中。
java 复制代码
@ConfigurationProperties(prefix = "example")
@Data
public class ExampleProperties {
    private String name;
    private int age;
}

ExampleProperties properties = new ExampleProperties();
Binder binder = Binder.get(environment);
binder.bind("example", Bindable.ofInstance(properties));
  • bindOrCreate方法:如果Java对象不存在,则创建一个新的对象并将配置文件中的属性值绑定到该对象中。
java 复制代码
ExampleProperties properties = Binder.get(environment)
        .bindOrCreate("example", Bindable.of(ExampleProperties.class));
  • bindProperty方法:将配置文件中的单个属性值绑定到Java对象的属性中。
java 复制代码
ExampleProperties properties = new ExampleProperties();
Binder binder = Binder.get(environment);
binder.bindProperty("example.name", Bindable.ofInstance(properties), String.class);
  • bindAnnotations方法:将Java对象中带有@ConfigurationProperties注解的属性绑定到配置文件中的属性值。
java 复制代码
@Data
@ConfigurationProperties(prefix = "example")
public class ExampleProperties {
    private String name;
    private int age;
}

ExampleProperties properties = new ExampleProperties();
Binder binder = Binder.get(environment);
binder.bindAnnotations(properties);
相关推荐
程序猿追14 分钟前
我搭了个网页工具:输入关键词,SERP API 自动吐出比价 Excel
后端
Lee川17 分钟前
RAG 实战:从一篇掘金文章出发,拆解检索增强生成的全链路
前端·人工智能·后端
Lee川30 分钟前
MCP 高德地图实战:当 AI 学会使用工具,一个协议如何重塑大模型的行动边界
前端·人工智能·后端
楼田莉子40 分钟前
C++17新特性:__had_include/属性/求值顺序规则
开发语言·c++·后端
程序员cxuan1 小时前
Codex 把我家烂网给优化后,我 TM 直接原地起飞了。
人工智能·后端·程序员
IT_陈寒1 小时前
Redis批量删除踩了坑,原来DEL命令不是万能的
前端·人工智能·后端
叫我少年2 小时前
C# 命名空间与 using 指令 — 文件范围、全局导入、别名
后端
我是一颗柠檬3 小时前
【MySQL全面教学】MySQL基础SQL语句Day3(2026年)
数据库·后端·sql·mysql·oracle
老毛肚4 小时前
Spring boot 特性和自写Reids组件
java·spring boot·后端
蝎子莱莱爱打怪4 小时前
👍🏻👍🏻6年381颗芯片+韬定律,华为重新定义半导体,为什么还有人喷???
后端·面试·程序员