Last active
March 6, 2016 18:10
-
-
Save amertkara/41b60c81fb4023d6a851 to your computer and use it in GitHub Desktop.
SpringBoot CommandLineRunner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.amertkara.springframework.multiplerunners.subcommands.analyzer; | |
import org.apache.commons.cli.*; | |
import org.springframework.boot.CommandLineRunner; | |
import org.springframework.stereotype.Component; | |
import javax.annotation.PostConstruct; | |
@Component | |
public class AnalyzerCommand implements CommandLineRunner { | |
private Options options; | |
private CommandLineParser parser; | |
private CommandLine cmd; | |
private HelpFormatter formatter; | |
/** | |
* Initiates the sub-command | |
*/ | |
@PostConstruct | |
public void init () { | |
options = new Options(); | |
parser = new DefaultParser(); | |
formatter = new HelpFormatter(); | |
final Option fileOption = Option.builder("f") | |
.argName("file") | |
.hasArg() | |
.desc("File to be analyzed") | |
.build(); | |
options.addOption(fileOption); | |
} | |
@Override | |
public void run(String... args) throws Exception { | |
if ("analyze".equals(args[0])) { | |
try { | |
cmd = parser.parse(options, args); | |
} catch (UnrecognizedOptionException | MissingArgumentException e) { | |
formatter.printHelp("sample", options); | |
System.exit(1); | |
} | |
if (cmd.hasOption("f") && !cmd.getOptionValue("f").isEmpty()) { | |
System.out.println("AnalyzerCommand is running on the file: " + cmd.getOptionValue("f")); | |
// Call the analyzer core | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Application | |
\-- Sub-command 1 (Runner1) | |
\-- Sub-command 2 (Runner2) | |
\-- ... | |
\-- Sub-command N (Runnern) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.boot.CommandLineRunner; | |
import org.springframework.core.Ordered; | |
import org.springframework.core.annotation.Order; | |
import org.springframework.stereotype.Component; | |
@Component | |
@Order(value = Ordered.LOWEST_PRECEDENCE) | |
public class Runner1 implements CommandLineRunner { | |
@Override | |
public void run(String... args) throws Exception { | |
System.out.println("Runner1 is running"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment