java.lang.IllegalStateException:遇到无效的@Scheduled方法:无法解析占位符@PropertySource(“ classpath:dev.yml”)

时间:2018-09-29 09:03:02

标签: spring-boot cron spring-cloud spring-cloud-config

我正在尝试加载以下cron-execution-expression:

---
####################### Cron-Job Every 2mins every day #######################
cron:
  exe:
    expression: 0 0/2 * * * ?

问题是,上面的cron表达式位于Spring-Cloud-Config(假设运行在端口:8001的Springboot Project A)的github存储库中。名为:microservice-dev.yml

项目B(端口:8002)在启动时加载项目A提供的所有配置,对此我感到很满意。但是,如何定位此表达式?

  

$ {cron.exe.expression}

@Component
//Couldn't get it to work with Spring-Cloud-Config
@PropertySource("classpath:microservice-dev.yml")
public class MergeCachedRecordsToDBImpl {
    private static final Logger LOGGER = LoggerFactory.getLogger(MergeCachedRecordsToDBImpl.class);

    //Couldn't get it to work with Spring-Cloud Config
    @Scheduled(cron = "${cron.exe.expression}")
    public void purgeExpired() {
        LOGGER.info("Cron-Job Notification....");
        LOGGER.info("Cron-Job executed at: {}", new Timestamp(new Date().getTime()));
    }
}

在某个时候,我可以使用它,但是我不确定如何?我正试图追溯自己的脚步。

现在我遇到了这个异常:

  

由以下原因引起:java.lang.IllegalStateException:遇到了无效的@Scheduled方法'purgeExpired':无法解析值“ $ {cron.exe.expression}”中的占位符'cron.exe.expression'

2 个答案:

答案 0 :(得分:1)

当前,春季靴子@PropertySource不支持yaml作为属性文件。

这是类似的问题-Spring @ConfigurationProperties not mapping list of objects

答案 1 :(得分:0)

好的,让它再次与.yml文件一起工作。快乐的日子。

在以下.yml文件中:

  

src / main / resources / bootstrap.yml

具有以下内容:

xyz@53d8d10a

在代码中,我用以下注释注释了我的类和方法:

---
spring:
  application:
    name: leaderboard
  profiles:
    active: dev

server:
  port: 8004

---
####################### Cron-Job Every 2mins every day #######################
cron:
  exe:
    expression: 0 0/2 * * * ?

结果:

@PropertySource("classpath:bootstrap.yml")
public class CronClass{
private static final Logger LOGGER = LoggerFactory.getLogger(CronClass.class);

   @Scheduled(cron = "${cron.exe.expression}")
   private void cornJob(){
        LOGGER.info("Cron-Job Notification....");
        LOGGER.info("Cron-Job executed at: {}", new Timestamp(new Date().getTime()));
   }
}

2018-09-29 11:19:00.007  INFO [leaderboard,66037f3d8052cf6b,66037f3d8052cf6b,false] 7937 --- [   scheduling-1] i.s.l.task.CronClass    : Cron-Job Notification....
2018-09-29 11:19:00.007  INFO [leaderboard,66037f3d8052cf6b,66037f3d8052cf6b,false] 7937 --- [   scheduling-1] i.s.l.task.CronClass    : Cron-Job executed at: 2018-09-29 11:19:00.007

2018-09-29 11:20:00.000  INFO [leaderboard,25cab214549b76a6,25cab214549b76a6,false] 7937 --- [   scheduling-1] i.s.l.task.CronClass    : Cron-Job Notification....
2018-09-29 11:20:00.000  INFO [leaderboard,25cab214549b76a6,25cab214549b76a6,false] 7937 --- [   scheduling-1] i.s.l.task.CronClass    : Cron-Job executed at: 2018-09-29 11:20:00.0

Evidence of .yml file with @PropertySource