Spring中@Value可读取config配置但ExpressionParser解析报空错误
问题根因
- 调用
expression.getValue()时未传入根对象,SpEL默认使用null作为评估根对象,尝试在null上查找config属性就会抛出你看到的Property or field 'config' cannot be found on null异常。 - 你混淆了Spring两种配置解析逻辑:
@Value("${config}")走的是属性占位符解析流程,会直接从Spring的Environment中读取@PropertySource加载的配置项,和SpEL(Spring表达式语言)是两套独立机制。 - 你手动
new出来的SpelExpressionParser是普通Java对象,未和Spring容器做任何绑定,本身不感知容器内的配置源、Bean等信息,不会自动关联properties文件里的配置项。就算给它传了普通根对象,直接写config作为表达式也读不到配置文件的值——SpEL默认不会把properties的key直接暴露为根对象属性。
解决方法
根据你的使用场景选以下任意一种即可:
方案1:直接使用已注入的配置值(最推荐,无冗余代码)
你已经通过@Value("${config}")把配置值注入到了成员变量s中,不需要额外做表达式解析,直接使用该变量即可:
@Override public void afterPropertiesSet() throws Exception { System.out.println(s); if("java".equals(s)) { System.out.println("[Configuration]: Java Configuration"); } else { System.out.println("[Configuration]: XML Configuration"); } }
方案2:必须手动解析SpEL时,绑定Spring上下文
如果确实需要在代码里动态用SpEL解析配置,需要先把Spring的上下文传入解析逻辑:
- 先在
StudentDAOImpl中注入Spring的Environment实例:
@Autowired private Environment environment;
- 解析表达式时将
environment作为根对象传入,通过getProperty方法读取配置:
@Override public void afterPropertiesSet() throws Exception { ExpressionParser expressionParser = new SpelExpressionParser(); Expression expression = expressionParser.parseExpression("getProperty('config')"); String result = expression.getValue(environment, String.class); System.out.println(result); // 后续业务判断逻辑 }
方案3:直接在注入时用SpEL完成解析
如果不需要动态拼接表达式,完全可以直接在@Value注解中使用SpEL语法,Spring会自动关联容器上下文完成解析,不需要手动创建解析器:
// 直接通过SpEL读取环境配置 @Value("#{environment.getProperty('config')}") private String config;
这种场景下直接用你原来的@Value("${config}")写法已经是最优解,不需要额外引入SpEL手动解析。
内容的提问来源于stack exchange,提问作者CoreDevilSon
相关产品推荐
相关产品推荐

