@ConfigurationProperties绑定配置信息至Array、List、Map、Bean的实现

网友投稿 787 2023-06-01

@ConfigurationProperties绑定配置信息至Array、List、Map、Bean的实现

@ConfigurationProperties绑定配置信息至Array、List、Map、Bean的实现

相关说明:

在SpringBoot中,我们可以通过以下几种方式获取并绑定配置文件中的信息:

@Value注解。

使用Environment。

@ConfigurationProhttp://perties注解。

通过实现ApplicationListener接口,注册-,进行硬编码获取,可参考:https://jb51.net/article/187407.htm

硬编码加载文件获取。

……

注:一般情况下,第一种、第二种就够用了;但是如果想直接从配置文件中获取到数组、list、map、对象的话,

第一种和第二种的支持性不太好,目前只能获取到数组、list,对map、bean的话,就有点束手无策了。

这时我们可以使用第三种方式进行获取。

环境说明:Windows10、IntelliJ IDEA、SpringBoot 2.1.5.RELEASE

@ConfigurationProperties注解获取配置信息并绑定到对象上示例:

准备工作:引入spring-boot-configuration-processor依赖

给出本人完整的pom.xml文件:

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.5.RELEASE

com.aspire.yaml-properties

yaml-properties

0.0.1-SNAPSHOT

yaml文件与properties文件语法示例

yaml文件与properties文件语法示例

1.8

org.springframework.boot

spring-boot-starter

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-configuration-processor

org.springframework.boot

spring-boot-maven-plugin

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.5.RELEASE

com.aspire.yaml-properties

yaml-properties

0.0.1-SNAPSHOT

yaml文件与properties文件语法示例

yaml文件与properties文件语法示例

1.8

org.springframework.boot

spring-boot-starter

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-configuration-processor

org.springframework.boot

spring-boot-maven-plugin

加载demo.properties文件中的信息绑定到bean,并注入容器示例:

项目结构说明:

注:application.yml其实在本次演示中,没有用到。不过本人给出了如何在yml文件中进行类似配置的

示例(见本文末尾)。

追注:如果要读取的是yml或yaml中的文件,那么最好是直接写在application.yml或

application.yaml文件中,写在其他yml文件中的话,可能导致读取失败。

(P.S.如果是写在其他yml或yaml文件中的话,只能通过最后一级key进行

定位,通过多级key可能定位不到。)

先给出一个等下会用到的Uer类:

注:上图中的注解是快速开发lombok注解,也可以不使用这些注解,自己写getter、setter等方法。

DemoConfig中是这样的:

注:上图中的@Data注解属于快速开发lombok注解,该注解不是必须的,也可以不要该注解,自己手写

getter、setter、toString等。

deme.properties中是这样的:

测试一下:

运行测试方法,控制台输出(为了方便观察,本人手动换行整理了一下输出的内容):

由此可见,成功将demo.peoperties文件中的信息绑定到bean上,并注入Spring容器成功!

拓展:

如果是application.yml(或application.yaml)文件,类似的,我们可以这么配置:

参考链接

https://jb51.net/article/187407.htm

测试代码托管链接

https://github.com/JustryDeng/CommonRepository/tree/master

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java项目实现寻找迷宫出路
下一篇:Java项目实现五子棋小游戏
相关文章

 发表评论

暂时没有评论,来抢沙发吧~