簡體   English   中英

通過 cmd 動態覆蓋默認 spring 引導 application.properties 與 application.properties

[英]Override default spring boot application.properties with application.properties through cmd dynamically

我想通過 cmd 覆蓋application.properties中定義的屬性以及application.properties中的現有其他屬性,但@Scheduled只允許提供預定義的值。

我需要的是通過命令行傳遞@Scheduled的參數,該命令行已經存在於application.properties中,它將更改@Scheduled中定義的默認值。

我的問題是,當我從 cmd 執行 jar 文件時,它正在獲取構建時@Scheduled中的值。 它不會覆蓋現有值@Scheduled值。 我想根據用戶需要覆蓋值。

spring代碼

@SpringBootApplication
@EnableScheduling
public class PSchedularApplication {

    public static void main(String[] args) {
        for(String s : args)
            System.out.println("arguments passed=>"+s);
        SpringApplication application = new SpringApplication(PSchedularApplication .class);
        if(!(args).equals(null))
        {
            application.setAddCommandLineProperties(true);
        }
        application.run(args);
    }
}

@Component  
public class TaskSchedular {
@Scheduled(cron="${cronExpression}")
    public void taskScheduling()
    {
        System.out.println("Welcome to task schedular " + new java.util.Date());
        moveFile();
    }
}

應用程序屬性

cronExpression=0 0/1 * * * *
pzsc.poll.cron.weekly=0 0/2 * * * *
pzsc.poll.cron.daily=0/30 * * * * *

在 cmd

java -jar PSchedular-0.0.1-SNAPSHOT.jar --cron=cronExpression
java -jar -Dserver.port=9999   your_jar_file.jar

請看看這個線程 有很多例子。

有幾種方法可以做到這一點,但我能想到的一種方法是使用外部化的應用程序屬性文件。 有關更多具體細節,請參閱https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-files

您的application.properties (在src/main/resources下)將具有默認屬性cronExpression 但是當你調用 JAR 時,你可以傳入一個系統屬性來告訴 Spring 一個附加的屬性文件在哪里,可能會覆蓋該cronExpression屬性。

java -jar <jar_name> -Dspring.config.additional-location=my-other-file.properties

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM