我有一个@ConfigurationProperties
注释的@Configuration
类,名为LibraryConfig. 它使用内部类作为属性/配置结构的类型定义。当类是内部类而不是独立类时,我得到"Elements[…]>错误/异常。为什么会这样,我该如何解决它?
application.yml
initdata:
library:
name: awesome library
books:
- title: Book1
author: Author Abc
- title: Book2
author: Author Xyz
LibraryConfiguration.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "initdata.library")
public class LibraryConfiguration {
private String name;
private List<Book> books;
// getters left out for simplicity of example
public void setName(String name) {
this.name = name;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public LibraryConfiguration() {
}
public static class Book {
private String title;
private String author;
public Book() {
}
// getters left out for simplicity of example
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
}
}
您要么创建一个独立的类,要么必须将内部类声明为static class
!否则,Spring不会将其视为"类型定义"。但是尝试创建它的一个实例——当然,它不能与给定的yml
配置一起工作。将代码更改为以下
// ...
public LibraryConfiguration() {
}
// This class MUST be static, otherwise Spring will tell "Elements [...] were left unbound".
// If it's static, it's just a "type definition";
// otherwise spring tries to create an insance
public static class Book {
private String title;
private
// ...