如何通过@ConfigurationProperties在一个类中读取多层嵌套配置?
使用@ConfigurationProperties读取嵌套配置属性
配置文件(application.yaml)
bookshop: properties: books: maxSize: title: 60 description: 800 price: commonDiscount: 10 sale: true
原@Value实现类
@Getter @Component public class BookSettingsGetter { @Value("${bookshop.properties.books.maxSize.title}") private Integer titleMaxSize; @Value("${bookshop.properties.books.maxSize.description}") private Integer descriptionMaxSize; @Value("${bookshop.properties.books.price.commonDiscount}") private Integer commonDiscountPercent; @Value("${bookshop.properties.books.sale}") private Boolean allowSaleBooks; }
问题
现在希望改用@ConfigurationProperties实现配置读取,公共前缀为bookshop.properties.books,目前仅能轻松获取sale属性,请问能否在一个类中获取其余嵌套属性?该如何实现?
当然可以在一个类里通过@ConfigurationProperties读取所有嵌套属性,核心是用内部类对应配置里的嵌套结构,配合前缀配置即可实现,具体步骤如下:
1. 编写配置读取类
通过静态内部类映射maxSize和price嵌套节点,同时指定公共前缀:
@Getter @Setter @Component @ConfigurationProperties(prefix = "bookshop.properties.books") public class BookSettingsProperties { // 直接映射sale属性 private Boolean sale; // 内部类映射maxSize节点 @Getter @Setter public static class MaxSize { private Integer title; private Integer description; } private MaxSize maxSize; // 内部类映射price节点 @Getter @Setter public static class Price { private Integer commonDiscount; } private Price price; }
2. 关键注意事项
- 必须提供
Setter方法(或使用构造器绑定,需添加@ConstructorBinding注解并编写全参构造器),Spring依赖Setter注入嵌套属性; - 内部类必须是
static修饰,否则Spring无法实例化嵌套类; @ConfigurationProperties的前缀要严格匹配配置的公共路径bookshop.properties.books;- 若需要IDE自动提示配置属性,可添加Spring Boot配置处理器依赖(如Maven的
spring-boot-configuration-processor)。
3. 使用示例
在业务类中注入配置类即可直接调用嵌套属性:
@Service public class BookService { private final BookSettingsProperties bookSettings; public BookService(BookSettingsProperties bookSettings) { this.bookSettings = bookSettings; } public void printBookSettings() { System.out.println("标题最大长度: " + bookSettings.getMaxSize().getTitle()); System.out.println("描述最大长度: " + bookSettings.getMaxSize().getDescription()); System.out.println("通用折扣比例: " + bookSettings.getPrice().getCommonDiscount()); System.out.println("是否允许售书: " + bookSettings.getSale()); } }
内容的提问来源于stack exchange,提问作者Ivan Fomkin
相关产品推荐
相关产品推荐

