- Spring Boot+Vue全栈开发实战
- 王松
- 372字
- 2025-02-20 10:40:51
2.6 类型安全配置属性
在2.5节中,读者已经了解到无论是Properties配置还是YAML配置,最终都会被加载到Spring Environment中。Spring提供了@Value注解以及EnvironmentAware接口来将Spring Environment中的数据注入到属性上,Spring Boot对此进一步提出了类型安全配置属性(Type-safe Configuration Properties),这样即使在数据量非常庞大的情况下,也可以更加方便地将配置文件中的数据注入Bean中。考虑在application.properties中添加如下一段配置:

将这一段配置数据注入如下Bean中:

代码解释:
• @ConfigurationProperties中的prefix属性描述了要加载的配置文件的前缀。
• 如果配置文件是一个YAML文件,那么可以将数据注入一个集合中。YAML将在2.7节介绍。
• Spring Boot采用了一种宽松的规则来进行属性绑定,如果Bean中的属性名为authorName,那么配置文件中的属性可以是book.author_name、book.author-name、book.authorName或者book.AUTHORNAME。
注意
以上的配置可能会乱码,需要对中文进行转码。在IntelliJ IDEA中,这个转码非常容易,在setting配置中进行简单配置即可,如图2-11所示。

图2-11
最后创建BookController进行简单测试:

注入Book,并将实例输出,如图2-12所示。

图2-12