简体   繁体   English

弹簧4力属性待定义

[英]Spring 4 force property to be defined

In spring I can retrieve property(defined in properties file) using getProperty method(of Environment) Eg 在春季,我可以使用(环境的) getProperty方法检索属性(在属性文件中定义)

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

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

however if the property is not defined then it returns null . 但是,如果未定义属性,则返回null We could make a null check and throw exception explicitly but is there some built-in method in spring to achieve it, so that application will throw exception if the property requested via getProperty method is not defined . 我们可以显式地进行null检查并抛出异常,但是在spring中是否有一些内置方法可以实现此目的,因此,如果未定义通过getProperty方法请求的属性,则应用程序将抛出异​​常。 I am using spring 4. 我正在使用Spring 4。

You can use getRequiredProperty which throws IllegalStateException if property is undefined. 您可以使用getRequiredProperty ,如果属性未定义,则抛出IllegalStateException。 Eg 例如

env.getRequiredProperty("foo");

If you want an error at Spring startup time, if you used something like 如果您想在Spring启动时出错,请使用类似

@Value("${foo.isEligible}")
protected boolean isFooEligible;

The Spring ApplicationContext will fail to startup if it can't resolve this SpEL expression 如果无法解析此SpEL表达式,Spring ApplicationContext将无法启动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Spring 数据 MongoDB 映射中强制属性顺序 - Force property order in Spring Data MongoDB mapping 如何获取Spring框架中属性文件中定义的所有键 - How to get all the keys defined in property file in spring framework 当 Spring 中未定义属性时如何匹配 - How to match when a property isn't defined in Spring 如果在多个属性文件中定义了一个属性,Spring 如何选择要使用的属性值? - How does Spring pick the property value to use if a property is defined in multiple property files? 使用Spring Context访问类路径属性和用户定义的属性文件? - Access class path property AND user-defined property file with Spring Context? Spring Boot 命令行属性不会覆盖 application.properties 中定义的属性 - Spring Boot command line property not overriding property defined in application.properties 春季:强制装豆 - Spring: force reload of a bean 弹力场初始化 - spring force fields initialization 在Spring上下文中(JNDI方式)定义属性占位符时,在幕后会发生什么? - What happens behind the scenes when a property placeholder is defined in a Spring context (JNDI-wise)? 尽管配置中定义了不正确的 bean 属性名称,Spring 如何检测正确的方法名称? - How does Spring detect the correct method name despite an incorrect bean property name defined in configuration?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM