如何编写命令行运行的程序

关闭 Web 容器

控制依赖

  • 最简单办法是 不添加 Web 相关依赖

配置方式

  • spring.main.web-application-type=none
    关闭web应用程序的一个支持

编程方式

  • SpringApplication
    • 设置 setWebApplicationType() 为none

  • SpringApplicationBuilder
    • 设置 web() 为none

  • 在调用 SpringApplication 的 run() 方法前
    设置 WebApplicationType 为none

常用工具类

不同的 Runner
功能一样 参数不一样

  • ApplicationRunner
    • 参数是 ApplicationArguments

  • CommandLineRunner
    • 参数是 String[]

如果有多个 ApplicationRunner 或者 CommandLineRunner 可以添加 @order 注解 去指定运行顺序
返回码

  • ExitCodeGenerator
    返回码0是正常结束 不是0为异常结束

例子

目录
在这里插入图片描述
代码

@Component
@Order(2)
@Slf4j
public class BarApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("Bar");
    }
}
@SpringBootApplication
public class CommandLineApplication {

	public static void main(String[] args) {
		new SpringApplicationBuilder(CommandLineApplication.class) //根据SpringApplicationBuilder把web中的WebApplicationType设置为none
				.web(WebApplicationType.NONE)
				.run(args);
		// 根据 application.properties 里的配置来决定 WebApplicationType
//		SpringApplication.run(CommandLineApplication.class, args);
	}
}
@Component
@Order(3)
@Slf4j
public class ExitApplicationRunner implements ApplicationRunner, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        int code = SpringApplication.exit(applicationContext);//取出返回码
        log.info("Exit with {}.", code);
        System.exit(code);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

@Component
@Order(1)
@Slf4j
public class FooCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("Foo");
    }
}
@Component
public class MyExitCodeGenerator implements ExitCodeGenerator {
    @Override
    public int getExitCode() {
        return 1;
    }//设置返回码
}

application.properties

spring.main.web-application-type=none
#关闭web应用程序支持

pom文件

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值