[英]Is there a way to validate @Value in spring boot?
I'm using @Value
to inject parameters from my properties file to variable in my application.我正在使用
@Value
将属性文件中的参数注入应用程序中的变量。
Because I'm not the only user in the application and I want to make the injection safety I need to validate the parameter before the injection.因为我不是应用程序中的唯一用户,并且我想让注射安全,所以我需要在注射前验证参数。
Example:例子:
properties file:属性文件:
example.string=str1,str2
app.java app.java
@Value(${example.string})
public String example;
the expected behavior in this case for example is to throw an exception because I assume "," id delimiter in array case例如,在这种情况下的预期行为是抛出异常,因为我假设“,”在数组情况下是 id 分隔符
I don't think you can directly with @Value
.我认为您不能直接使用
@Value
。 But you could do something like this, which will fail on startup if validation fails:但是你可以做这样的事情,如果验证失败,它将在启动时失败:
@Validated
@ConfigurationProperties(prefix="my.prefix")
public class AppProperties {
//Validation annotations here
//@NotEmpty
//@MyCustomValidation
private String exampleString;
// getters / setters
}
I don't think you can do this before the injection, try to use the post construct method我不认为你可以在注入之前这样做,尝试使用 post 构造方法
you can do some thing like that:你可以做这样的事情:
@PostConstruct
public void validateValue() {
if (someProperty.contains(",")) {
throw new MyException("error");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.