Ser*_*046 -3 java spring spring-aop spring-annotations
我是Java/Spring的新手.我需要从配置中读取一些值,但如果它不存在则应该失败.现在我有以下代码:
public class SomeClass {
@Value("${some.property:#{null}}")
private String someProperty;
public void someMethod() throws Exception {
if (someProperty == null) throw new AopConfigException("The property must be set");
}
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我需要添加额外的if块.我可以写那样的东西吗?
@Value("${some.property:#{throw new AopConfigException(\"The property must be set\")}}")
private String someProperty;
Run Code Online (Sandbox Code Playgroud)
要么
@Value("${some.property:#{throwException()}}")
private String someProperty;
private static void throwException() {
throw new AopConfigException("The property must be set");
}
Run Code Online (Sandbox Code Playgroud)
立即失败
更新:
如果我没有使用下面建议的某个默认值,那么它对我来说仍然不会失败.我没有java.lang.IllegalArgumentException:
默认情况下需要@Value.所以,只需使用
@Value("${some.property}")
Run Code Online (Sandbox Code Playgroud)
代替
@Value("${some.property:#{null}}")
Run Code Online (Sandbox Code Playgroud)
因此,如果该属性不存在,您的应用程序将无法启动此类异常:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'invalid.value' in value "${invalid.value}"
Run Code Online (Sandbox Code Playgroud)
更新:如果你想拥有一个密钥,它可以是空的,如下所示:
some.property=
Run Code Online (Sandbox Code Playgroud)
并且如果该属性为空,则要抛出异常,然后使用@PostConstruct如下:
@PostConstruct
public void validateValue() {
if (someProperty.isEmpty()) {
throw new MyNiceException("error");
}
}
Run Code Online (Sandbox Code Playgroud)
更新更新:如果你想初始化null,以防如果没有key的注册表
@Value("${some.property:#{null}}")
private String someProperty;
Run Code Online (Sandbox Code Playgroud)
然后这样做:
@PostConstruct
public void validateValue() {
if (someProperty == null) {
throw new IllegalArgumentException("error");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1569 次 |
| 最近记录: |