javaspringspring-bootspring-annotationsspring-el

Spring @Value default fails to evaluate expression


I need to set up thread pool size for scheduled tasks based on either specified property or available resources. So, I wrote the following code:

@EnableScheduling
@Configuration
public class TaskScheduler{
    
    @Value("${thread.pool.size:#{Runtime.getRuntime().availableProcessors() - 1}}")
    private int threadPoolSize;
    
    @Autowired
    TaskDataRepository repository;
    ...
}

However, when I start the code I am getting

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)

Can someone please point out what is wrong with my expression? Thank you.


Solution

  • Static methods cannot be accessed directly, you should use T operator to get a reference to the Runtime type.

    @Value("${thread.pool.size:#{T(Runtime).getRuntime().availableProcessors() - 1}}")
    private int threadPoolSize;