【发布时间】:2018-07-11 15:02:54
【问题描述】:
我是 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");
}
}
它工作正常,但我需要添加额外的 if 块。我可以写这样的东西吗?
@Value("${some.property:#{throw new AopConfigException(\"The property must be set\")}}")
private String someProperty;
或
@Value("${some.property:#{throwException()}}")
private String someProperty;
private static void throwException() {
throw new AopConfigException("The property must be set");
}
立即失败
更新:
如果我不使用下面建议的一些默认值,那么它对我来说仍然不会失败。我没有java.lang.IllegalArgumentException:
【问题讨论】:
-
只使用@Value("${some.property}") 而不是@Value("${some.property:#{null}}")
-
spring 会查找该值,如果不存在则抛出异常
-
它返回 "${some.property}" 而不是我的异常
-
如果设置了属性,
importDataPath的值是多少?为了使属性替换起作用,您需要配置一个PropertyPlaceholderConfigurerbean。 -
@dpr
${import.data.path}如截图所示
标签: java spring spring-aop spring-annotations