java - Spring boot YAML 配置未读取所有值

标签 java spring spring-boot configuration yaml

我正在尝试在 Spring Boot 1.5.1 项目中设置并使用 YAML 作为配置文件。

我的 YAML 文件如下所示:

hue:
    user: cdKjsOQIRY8hqweAasdmx-WMsn
    ip: "http://192.168.1.69"
    scenes:
        sunstatus:
            enabled: true
            id: 93yv8JekmAneCU9
            group: 1
        disable:
            enabled: true
            id: 93yv8JekmAneCU9
            group: 6

读取hue.getUser() 效果非常好。但是,hue.getScenes() 由于某种原因返回 null。我的 Hue 配置的 Java 代码如下所示:

@Configuration
@ConfigurationProperties(prefix = "hue")
public class Hue {
    private String user;
    private String ip;
    private Scenes scenes;

    /*
     * Getters and setters of course
     */

    public class Scenes {
        private Sunstatus sunstatus;
        private Disable disable;

        /*
         * Getters and setters
         */

        public class Sunstatus {
            private boolean enabled;
            private String id;
            private String group;

            /*
             * Getters and setters
             */
        }

        public class Disable {
            private boolean enabled;
            private String id;
            private String group;

            /*
             * Getters and setters
             */
        }
    }
}

我也尝试用前缀注释每个类,格式均为hue.scenes.sunstatus、scenes.sunstatus 和sunstatus。

此外,我还尝试使用 @Value 注释,但没有任何运气。

如果我将数据保存在 application.yml 或外部文件中,结果是相同的。始终只能到达 getUser()。

我在这里做错了什么?

最佳答案

我发现您正在使用公共(public)非内部类进行嵌套配置,因此您应该添加 @NestedConfigurationProperty :

public class Scenes {

    @NestedConfigurationProperty
    private Sunstatus sunstatus;

    @NestedConfigurationProperty
    private Disable disable;

Nested properties

You can use the @NestedConfigurationProperty annotation on a field to indicate that a regular (non-inner) class should be treated as if it were nested.

因此,要么添加注释(如果您打算在其他地方使用这些类),要么将它们设置为public static

关于java - Spring boot YAML 配置未读取所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42145946/

相关文章:

java - 为什么 jpa/hibernate 在保存从 "select-then-update"方法检索的实体时仍然执行 "findBy",似乎它已分离

java - 使用 spring mvc 和 jpa 将数组转换为映射

java - 如何用Java在cassandra中实现批处理

java - 如何预热java类以避免首次调用缓慢?

java - KDB+ 不区分大小写的查询

java - 使用子对象 Java 访问父字段

java - 为什么 JPA 有 @Transient 注解?

java - 删除目录java中的某些文件夹

java - 无法通过链接到达 Spring

java - 用于 noscript 中使用的 spring 模型变量的 thymeleaf 语法