package com.three.sevenths.first;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.annotation.Order;
@SpringBootApplication
public class CommandApplication {
private static Logger logger = LoggerFactory.getLogger(CommandApplication.class);
public static void main(String[] args) {
SpringApplication.run(CommandApplication.class, args);
}
}
以上代码就是启动一个Springboot进程,要进行命令行程序的运行,只需要开发实现CommandLineRunner 接口的代码,可以直接使用spring的自动启动,依赖注入等特性,如下我们开发第一个命令行程序,实现run方法的参数就可以自动接收命令行参数,
package com.three.sevenths.first;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class Command1 implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(Command1.class);
@Override
public void run(String... args) throws Exception {
logger.info("Command1 run:");
for (String arg : args) {
logger.info("args:" + arg);
}
}
}
同时可以执行多个命令行程序,使用@Order设置执行顺序,开发第二个Command,注入SomeComponent实例
package com.three.sevenths.first;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class Command2 implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(Command2.class);
@AutoWired
SomeComponent someComponent;
@Override
public void run(String... args) throws Exception {
logger.info("Command2 run:");
for (String arg : args) {
logger.info("args:" + arg);
}
someComponent.execute("request");
}
}