Spring 4强制属性被定义

时间:2015-01-21 18:57:36

标签: java spring

在春天,我可以使用getProperty方法(环境)来检索属性(在属性文件中定义),例如

@PropertySource("classpath:app.properties")
public class Config{
    @Autowired
    Environment env;

@Bean 
public Foo foo(){
 env.getProperty("foo.isEligible")
//.... return foo.
}
}

但是如果未定义属性,则返回null。我们可以进行空检查并显式抛出异常,但是在Spring中有一些内置方法来实现它,因此如果未定义通过getProperty方法请求的属性,应用程序将抛出异​​常。我正在使用春天4。

2 个答案:

答案 0 :(得分:0)

如果未定义property,则可以使用getRequiredProperty抛出IllegalStateException。 E.g。

env.getRequiredProperty("foo");

答案 1 :(得分:0)

如果您希望在Spring启动时出现错误,请使用

之类的内容
@Value("${foo.isEligible}")
protected boolean isFooEligible;

如果Spring ApplicationContext无法解析此SpEL表达式

,它将无法启动