Spring @Value默认表达式解析失败,请求排查问题原因
我需要根据指定配置属性或可用CPU资源设置定时任务的线程池大小,编写了如下代码:
@EnableScheduling @Configuration public class TaskScheduler{ @Value("${thread.pool.size:#{Runtime.getRuntime().availableProcessors() - 1}}") private int threadPoolSize; @Autowired TaskDataRepository repository; ... }
启动代码时出现如下报错:
2024-01-31 11:59:04.217 [METADATA-DEV] [main] [WARN ]
o.s.c.a.AnnotationConfigApplicationContext : %PARSER_ERROR[enc]
2024-01-31 11:59:04.231 [METADATA-DEV] [main] [INFO ]
o.s.b.a.l.ConditionEvaluationReportLogger : %PARSER_ERROR[enc]
2024-01-31 11:59:04.259 [METADATA-DEV] [main] [ERROR ]
o.s.boot.SpringApplication : %PARSER_ERROR[enc]
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'taskScheduler': Unsatisfied dependency
expressed through field 'treadPoolSize': Expression parsing failed at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:772)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:752)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145)
提示表达式解析失败,请问我的表达式哪里存在问题?
1. SpEL类引用语法错误
Spring SpEL中直接引用Java类必须使用T()包裹全限定类名,你直接写Runtime.getRuntime()会被Spring识别为不存在的变量或Bean,导致表达式解析失败。修正后的写法如下:
@Value("${thread.pool.size:#{T(java.lang.Runtime).getRuntime().availableProcessors() - 1}}") private int threadPoolSize;
2. 字段名拼写检查
报错信息中明确提到field 'treadPoolSize',但你代码里的字段名是threadPoolSize(注意tread与thread的拼写差异)。如果这不是日志输出的笔误,需检查代码中字段名是否与依赖注入逻辑匹配,避免因拼写不匹配导致注入失败。
内容的提问来源于stack exchange,提问作者Gary Greenberg

