命令行调用springboot服务_使用Springboot启动命令行程序

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");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值