有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用Spel通过另一个Spring值来计算Spring值

我有一个来自应用程序的属性。属性

housekeeping.shortInterval=true

我想计算java代码中的一个值,这个值依赖于:

    @Scheduled(fixedRateString = "#{housekeeping.shortInterval == true ? 60000 : 3600000*24}")
    public int doHousekeeping()
    {...}

不幸的是,这不起作用。我做错了什么

第二个问题:编写测试以测试此表达式的输出的最简单方法是什么


共 (1) 个答案

  1. # 1 楼答案

    第一个问题的答案:

    您需要将属性括在${}之间,如下例所示:

    @Scheduled(fixedRateString = "#{${housekeeping.shortInterval} == true ? 60000 : 3600000*24}")
    

    我已经在我的电脑上测试过了,它工作正常

    回答你的第二个问题:

    请参阅下面的示例,以在Spring Boot中测试CRON。修改调度程序方法以存储CRON值-

    import java.time.LocalDateTime;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import lombok.extern.log4j.Log4j2;
    
    @Component
    @Log4j2
    public class ScheduleTask {
        @Value("${housekeeping.shortInterval}")
        private boolean shortInterval;
        private long cronValue;
    
        @Scheduled(fixedRateString = "#{${housekeeping.shortInterval} == true ? 60000 : 3600000*24}")
        public void scheduleTask() {
            this.cronValue = ((shortInterval == true) ? 60000 : 3600000 * 24);
            log.info("Executed at {}", LocalDateTime.now());
        }
    
        public long getCronValue() {
            return this.cronValue;
        }
    }
    

    测试时检查CRON值:

    import static org.junit.jupiter.api.Assertions.assertEquals;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    public class ScheduledTaskTest {
    
        @Autowired
        ScheduleTask task;
    
        @Test
        public void scheduleTask_Cron_Test() {
            //Test CRON value
            assertEquals(task.getCronValue(), 60000l);
        }
    }