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);
相关推荐
孤雪心殇3 小时前
简单易懂,解析Go语言中的Map
开发语言·数据结构·后端·golang·go
White graces3 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
小突突突4 小时前
模拟实现Java中的计时器
java·开发语言·后端·java-ee
web137656076434 小时前
Scala的宝藏库:探索常用的第三方库及其应用
开发语言·后端·scala
闲猫5 小时前
go 反射 interface{} 判断类型 获取值 设置值 指针才可以设置值
开发语言·后端·golang·反射
奋斗的袍子0075 小时前
Spring AI + Ollama 实现调用DeepSeek-R1模型API
人工智能·spring boot·深度学习·spring·springai·deepseek
LUCIAZZZ6 小时前
EasyExcel快速入门
java·数据库·后端·mysql·spring·spring cloud·easyexcel
wolf犭良6 小时前
19、《Springboot+MongoDB整合:玩转文档型数据库》
数据库·spring boot·mongodb
Asthenia04126 小时前
依托IOC容器提供的Bean生命周期,我们能在Bean中做些什么?又能测些什么?
后端
Ase5gqe6 小时前
Spring中的IOC详解
java·后端·spring