当前位置: 首页 > 知识库问答 >
问题:

将ConfigurationProperties与内部类一起使用会导致“属性未绑定”异常

凌联
2023-03-14

我有一个名为LibraryConfig的带有注释的配置属性类。它使用内部类作为属性/配置结构的类型定义。当类是内部类而不是独立类时,我得到“元素[…]“未绑定”错误/异常。为什么会这样?我如何修复它?

application.yml

initdata:
  library:
    name: awesome library
    books:
      - title: Book1
        author: Author Abc
      - title: Book2
        author: Author Xyz

库配置。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;
        }
    }
}

共有1个答案

屈浩波
2023-03-14

您要么创建一个独立类,要么必须将内部类声明为静态类!否则,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 
// ...
 类似资料:
  • 我想通过使用@ConfigurationProperties注释将我的Application.Properties自动绑定到一个类中。首先,我尝试了@value注释,并能够将属性值注入类变量。但是,@ConfigurationProperties没有将属性注入到值中。 我的应用程序.属性: application.java ConfigBinder.java 输出: 这样的执行到底出了什么问题?

  • 如何在Spring Boot中将属性绑定到POJO? POJO类是第三方库类-我不能将@ConfigurationProperties放在那里 我知道一些实用程序类,如DataBinder,可以帮助,但可能有一个更快的方法。提前谢谢你。

  • 问题内容: 以下代码基于javadocs中java.util.zip.Deflater给出的示例。我所做的唯一更改是创建一个称为dict的字节数组,然后使用setDictionary(byte [])方法在Deflater和Inflater实例上设置字典。 我看到的问题是,当我使用与Deflater使用的数组完全相同的数组调用Inflater.setDictionary()时,出现了Illegal

  • 我使用的是一个存储字符串的ThreadLocal对象。我将String值设置为过滤器中的ThreadLocal对象,该对象将截取符合特定条件的所有请求。另外,我将ThreadLocal的字符串值设置为HttpSession作为属性。 那么,有什么方法可以改变实现,使多个会话不使用同一个线程呢? 编辑:添加示例代码

  • 我有以下测试: 属性位于中,看起来如下: 但是,我一直得到第25行,这正是具有初始化的行: Java.lang.NullPointerException位于com.example.estrans.esjavaapitests.(esjavaapitests.Java:25)位于sun.reflect.nativeConstructorAccessorImpl.newInstance0(原生方法)位

  • 实际上,我们使用Google IdP作为应用程序的SSO/SAML身份验证类型。我们已将其配置为将用户连接到应用程序,并且运行良好。但最近,我们还想要求用户对应用程序生命周期中可能发生的不同操作进行重新验证。 更详细地说,当我们向Google Idp发送SAML请求时,我们在节点“AuthnRequest”中添加了属性ForceAuthn=“true”,我们还添加了AuthnContextClas