当前位置: 首页 > news >正文

Spring Boot中的Binder类

介绍

Spring Boot中的Binder类是一个用于绑定属性的工具类。它可以将配置文件中的属性值绑定到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对象中。如果属性不存在,则使用默认值。


配置文件中属性:

myconfig.name=John
myconfig.age=25

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;@Configuration
public class AppConfig {@Autowiredprivate Environment environment;public MyConfig myConfig() {return new MyConfig(environment);}
}

常用方法

  • bind方法:将配置文件中的属性值绑定到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对象不存在,则创建一个新的对象并将配置文件中的属性值绑定到该对象中。
ExampleProperties properties = Binder.get(environment).bindOrCreate("example", Bindable.of(ExampleProperties.class));
  • bindProperty方法:将配置文件中的单个属性值绑定到Java对象的属性中。
ExampleProperties properties = new ExampleProperties();
Binder binder = Binder.get(environment);
binder.bindProperty("example.name", Bindable.ofInstance(properties), String.class);
  • bindAnnotations方法:将Java对象中带有@ConfigurationProperties注解的属性绑定到配置文件中的属性值。
@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);
http://www.lryc.cn/news/179871.html

相关文章:

  • leetcode之打家劫舍
  • 走进Spring的世界 —— Spring底层核心原理解析(一)
  • 快看看你的手机有没有:谷歌Android全面封杀此类软件!
  • spark ui 指南
  • 【分布式事务】
  • linux 清除卸载jenkins
  • 番外4:VMware安装
  • Oracle 19.20 patch 注意事项
  • ElementUI之增删改及表单验证
  • 【Java 进阶篇】深入理解 JDBC:Java 数据库连接详解
  • Web开发-session介绍
  • 基于Qt Creator开发的坦克大战小游戏
  • 小说推文和短剧推广以及电影达人带货电影票
  • 朴素贝叶斯分类(下):数据挖掘十大算法之一
  • 9.30作业
  • [GWCTF 2019]枯燥的抽奖
  • vue3中sync修饰符的使用
  • Qt全屏显示与退出
  • OpenCV之直线曲线拟合
  • 2023年哪款PDF虚拟打印机好用?
  • Redis各数据类型特定的命令和用法 1.0版本
  • 卫星图像应用 - 洪水检测 使用DALI进行数据预处理
  • 为什么字节大量用GO而不是Java?
  • Hive SQL初级练习(30题)
  • NSSCTF做题(6)
  • 公众号商城小程序的作用是什么
  • 关于 FOCA
  • TVP专家谈腾讯云 Cloud Studio:开启云端开发新篇章
  • 2023-09-27 Cmake 编译 OpenCV+Contrib 源码通用设置
  • ACGAN