【问题标题】:Spring Boot start the application with configurations checkSpring Boot 使用配置检查启动应用程序
【发布时间】:2018-11-07 08:24:25
【问题描述】:

这是关于Spring Boot 的应用程序。如果有人配置了错误的Yaml file,我想在开始时检查并通知用户。我想问你们中的一些人,

  1. 这是实现它的正确方法吗?
  2. RuntimeException 是正确的选择吗?
  3. 我是否正确使用了lombok 注释?

谢谢

@Component
@ConfigurationProperties
@Data
@NoArgsConstructor
public class ApplicationProperties{

    @Data
    @NoArgsConstructor
    public static class Something {
        private String name;

        @Setter(AccessLevel.NONE)
        private int width;

        @Setter(AccessLevel.NONE)
        private int height;

        public void setWidth(int width) throws Throwable {
            if (0 > width || 100 < width) {
                throw new RuntimeException("The width should be between 0 and 100.");
            }
            this.width = width;
        }

        public void setHeight(int height) throws Throwable {
            if (0 > height || 250 < height) {
                throw new RuntimeException("The height should be between 0 and 250.");
            }
            this.height = height;
        }
    }
}

【问题讨论】:

    标签: spring-boot lombok


    【解决方案1】:

    首先,欢迎来到 SO!让我解释一下如何验证应用程序属性。有一种简单的方法可以使用验证注释来实现这一点。 @ConfigurationProperties 支持 JSR-303 bean 验证:

    @ConfigurationProperties("prefix")
    public class MyProperties {
    
        @Max(100)
        @Min(0)
        private Integer width;
    
        @Max(100)
        @Min(1)
        private Integer height;
    }
    

    请注意,如果验证引发异常,此方法将导致应用程序启动失败。

    其次,要了解这是否是正确的方法,您必须描述您的用例。我个人会坚持现有标准并使用验证注释流程。

    最后,关于您的 lombok 注释。您可以在全局范围内使用 @Getter@Setter 注释,也可以像这样将它们放在您的字段中以指定细粒度的访问权限。

    我不是@Data 注释的忠实拥护者,因为它可能会生成一些您可能不需要(或者可能再次取决于您的使用)想要的额外方法。我记得在使用生成的toString 方法时遇到了嵌套实体和循环依赖的一些问题。

    【讨论】:

    • 如果您通过EnableConfigurationProperties(MyProperties.class) 显式启用ConfigurationProperties,也可以删除@Configuration
    • 谢谢你们俩。我喜欢这个解决方案,但在我的情况下它不起作用。你能给我一些提示吗,为什么会这样?
    猜你喜欢
    • 2021-07-21
    • 2018-11-27
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2019-09-09
    • 2016-06-12
    相关资源
    最近更新 更多