1

I want to override properties defined in application.properties through cmd with existing other in application.properties , but @Scheduled only allows to provide predefined values.

What I need is to pass the argument for @Scheduled through command line which already exists in application.properties and It will going to change the default value defined in @Scheduled.

My question is that when I am executing jar file from cmd It is taking value present in @Scheduled at the time of build. It is not overriding the existing value @Scheduled value. I want to override value as per user need.

spring code

@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();
    }
}

Application.properties

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

in cmd

java -jar PSchedular-0.0.1-SNAPSHOT.jar --cron=cronExpression
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
jyotsna
  • 51
  • 9
  • Well for starters `--cron=cronExpression` should be `--cronExpression=your-expression`, it should match the name of the attribute to provide the schedule. Also this is already supported out of the box, so the "clever" code you wrote in your main, doesn't actually help, it only complicates things. – M. Deinum Apr 20 '21 at 08:11

2 Answers2

1

There's a couple ways of doing this, but one way I can think of is to use externalized application properties file. See https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-files for more specific details.

You would have your application.properties (under src/main/resources) with the default property cronExpression. But when you invoke the JAR, you could pass in a system property to tell Spring where an additional properties file is with possible overrides for that cronExpression property.

java -jar <jar_name> -Dspring.config.additional-location=my-other-file.properties
Tim Tong
  • 194
  • 3
  • 6
1
java -jar -Dserver.port=9999   your_jar_file.jar

Please take a look at this thread. There's a many example.

Dharman
  • 30,962
  • 25
  • 85
  • 135