小编cra*_*wor的帖子

SpEL如何在方法调用中使用参数?

我有一个使用 Spring Scheduler 的应用程序,我想从数据库获取 cron 表达式。我让它在没有参数的情况下工作,但我需要在调用中使用参数才能从数据库(计划名称)获取正确的计划。我尝试了几个不同的版本但没有成功。请参阅下面的工作和非工作代码作为我正在尝试做的事情的示例。

以下代码正在运行:

@Configuration
@EnableScheduling
public class ApplicationConfig {

    @Autowired
    SchedulePropertiesRepository spRepository;

    @Bean   
    public String getCronExpression() {
        ScheduleProperties sp = spRepository.findByScheduleName("date");
        return sp.getCron();
    }
}
Run Code Online (Sandbox Code Playgroud)

@Scheduled(cron = "#{@getCronExpression}")
private void cronSchedule() {
     log.info("The time is now {}", dateFormat.format(new Date()));
}
Run Code Online (Sandbox Code Playgroud)

不过,我想传递计划名称的参数,例如:

@Configuration
@EnableScheduling
public class ApplicationConfig {

    @Autowired
    SchedulePropertiesRepository spRepository;

    @Bean   
    public String getCronExpression(String scheduleName) {
        ScheduleProperties sp = spRepository.findByScheduleName(scheduleName);
        return sp.getCron();
    }
}
Run Code Online (Sandbox Code Playgroud)

@Scheduled(cron = "#{@getCronExpression('date')}")
private void cronSchedule() {
     log.info("The time is …
Run Code Online (Sandbox Code Playgroud)

java spring spring-el spring-boot

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×1

spring ×1

spring-boot ×1

spring-el ×1