Spring boot Spring Boot使用配置检查启动应用程序
它是关于一个Spring boot Spring Boot使用配置检查启动应用程序,spring-boot,lombok,Spring Boot,Lombok,它是关于一个springboot应用程序的。如果有人将Yaml文件配置为false,我想在开始时检查并通知用户。我想问你们中的一些人 这是正确的实施方式吗 RuntimeException是正确的选择吗 我是否正确使用了lombok注释 多谢各位 @Component @ConfigurationProperties @Data @NoArgsConstructor public class ApplicationProperties{ @Data @NoArgsConstru
springboot
应用程序的。如果有人将Yaml文件配置为false,我想在开始时检查并通知用户。我想问你们中的一些人
这是正确的实施方式吗
RuntimeException
是正确的选择吗
我是否正确使用了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;
}
}
}
@组件
@配置属性
@资料
@诺尔格构装师
公共类应用程序属性{
@资料
@诺尔格构装师
公共静态类某物{
私有字符串名称;
@Setter(AccessLevel.NONE)
私有整数宽度;
@Setter(AccessLevel.NONE)
私人内部高度;
公共void setWidth(int-width)抛出可丢弃{
如果(0>宽度| | 100<宽度){
抛出新的RuntimeException(“宽度应该在0到100之间”);
}
这个。宽度=宽度;
}
public void setHeight(int height)抛出可丢弃{
如果(0>高度| 250<高度){
抛出新的RuntimeException(“高度应该在0到250之间”);
}
高度=高度;
}
}
}
首先,欢迎来到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
,谢谢大家。我喜欢这个解决方案,但在我的情况下不起作用。你能给我一些提示吗?为什么?