我有一个像这样的最终配置类:
@Value // <- lombok-annotation
@ConstructorBinding
@ConfigurationProperties("my-app.conf")
public class MyProperties {
Duration reloadPeriod;
}
我想在@Scheduled
字段中像这样使用reloadPeriod
:
@Service
public class MyService {
@Scheduled(fixedDelayString = "#{myProperties.reloadPeriod}")
public void doSomeRecurrentStuff() {
// some work
}
}
但是这个设置总是会失败,并出现以下错误:
由:org.springframework.expression. spell . spelevaluationexception: EL1008E:属性或字段'myProperties'无法在类型为'org.springframework.beans.factory.config的对象上找到。BeanExpressionContext' -也许不是公共的或无效的?
当我添加"中间bean"时;这样的:
@Configuration
public class MyConfigClass {
@Bean("reloadPeriod")
Duration reloadPeriod(MyProperties props) {
return props.getReloadPeriod();
}
}
,然后我可以引用它没有任何问题,像这样:@Scheduled(fixedDelayString = "#{reloadPeriod}")
tldr;如何访问"like beans"由@ConstructorBinding
通过SpEL创造?
您可以使用beanFactory
根据其类型获取配置属性bean。
@Scheduled(fixedDelayString =
"#{beanFactory.getBean(T(com.package.MyProperties)).reloadPeriod}")
public void doSomeRecurrentStuff() {
// ...
}
或者,实现SchedulingConfigurer
以编程方式设置计划任务。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
@Autowired
private MyProperties myProperties;
void doSomeRecurrentStuff() {
// some work
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addFixedDelayTask(this::doSomeRecurrentStuff,
myProperties.getReloadPeriod());
}
}