大致:想要使用Spring Shell,则项目需要是 Spring Boot项目,下面贴出结构和代码
1.POM依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!--如果原先是Maven项目,不是Spring Boot项目,则这个Parent依赖需要加上--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>my</groupId> <artifactId>SpringShellDemo</artifactId> <version>1.0-SNAPSHOT</version> <name>SpringShellDemo</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <java.version>1.8</java.version> </properties> <!--下面是依赖项--> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.1.1.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.shell</groupId> <artifactId>spring-shell-starter</artifactId> <version>2.0.0.RELEASE</version> </dependency> </dependencies> <!--添加Spring BootMaven插件--> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.0.0.RELEASE</version> </plugin> </plugins> </build> </project>
2.DemoApplication.java Spring Boot启动类
package command; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
3.MyCommand.java 命令类
package command; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; @ShellComponent public class MyCommandDemo { @ShellMethod("Add two intergers together.") public int add(int a,int b){ return a+b; } }
如果IDE工具是IDEA,执行
mvn clean install -DskipTests:跳过测试,直接安装Install java -jar target**.jar(安装的jar包名称):执行jar包
问题:如果启动时出现未找到主程序,则需查看主POM文件是否添加Parent的Spring Boot依赖