[JAVA] Notes d'utilisation de Spring Shell

Qu'est-ce que Spring Shell?

--Un framework qui facilite la création d'outils REPL

environnement

OS Windows 10

Java 1.8.0_162

Hello World

la mise en oeuvre

build.gradle


buildscript {
	ext {
		springBootVersion = '2.0.0.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

repositories {
	mavenCentral()
}

dependencies {
	compile('org.springframework.shell:spring-shell-starter:2.0.0.RELEASE')
}

bootJar {
	baseName = 'sample'
}

SampleApplication.java


package sample.spring.shell;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(SampleApplication.class, args);
	}
}

SampleCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello Spring Shell!!");
    }
}

Résultat d'exécution

> gradle build

> java -jar build\libs\sample.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

(Omis)
shell:>【hello】
Hello Spring Shell!!
shell:>【exit】
(Omis)

>

La description

Commandes intégrées

commander La description
clear Effacer ce qui est actuellement affiché dans le shell
exit, quit Sortez du shell
help Obtenir de l'aide
script Lire et exécuter des commandes à partir d'un fichier
stacktrace Afficher la trace de la pile de la dernière erreur

À quoi cela ressemble lorsque vous exécutez l'aide


shell:>help
AVAILABLE COMMANDS

Built-In Commands
        clear: Clear the shell screen.
        exit, quit: Exit the shell.
        help: Display help about available commands.
        script: Read and execute commands from a file.
        stacktrace: Display the full stacktrace of the last error.

Sample Commands
        hello: Hello World

Fonctionnement de base de la coque

Raccourci

Raccourci Détails de l'opération
Ctrl + u Supprimer à gauche du curseur
Ctrl + k Retirer la droite du curseur
Ctrl + a Déplacez le curseur au début de la ligne
Ctrl + e Déplacer le curseur à la fin de la ligne
Ctrl + w Supprimer jusqu'au mot précédent
Ctrl + d Supprimer le caractère à la position du curseur
Ctrl + f Avancez le curseur d'un
Ctrl + b Reculer le curseur d'un
Alt + f Avancer le curseur d'un mot
Alt + b Déplacer le curseur d'un mot en arrière

Passer une valeur avec des espaces vides

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class GreetingCommands {

    @ShellMethod("Hello World")
    public void hello(String text) {
        System.out.println(text);
    }
}

Résultat d'exécution


shell:>【hello "foo bar"】
foo bar

shell:>【hello 'foo bar'】
foo bar

shell:>【hello "foo 'bar'"】
foo 'bar'

shell:>【hello 'foo "bar"'】
foo "bar"

shell:>【hello "foo \"bar\""】
foo "bar"

shell:>【hello 'foo \'bar\''】
foo 'bar'

--Si vous souhaitez passer une chaîne contenant des espaces vides comme argument, placez la chaîne entre guillemets simples (`` '') ou doubles (" ).

Échapper aux espaces vides


shell:>【hello foo\ bar】
foo bar

Entrée multiligne

Résultat d'exécution


shell:>【hello "abc】
dquote> 【defg】
dquote> 【hijk"】
abc defg hijk

--Si vous insérez un saut de ligne pendant que les guillemets sont lancés, vous serez toujours invité à entrer des caractères.

Saisie complétée par onglet

springshell.gif

--Lorsque vous entrez Tab, la saisie semi-automatique fonctionne à divers endroits. --Lorsque les candidats sont affichés, continuez à saisir «Tab» pour déplacer le curseur vers les options dans l'ordre.

Inclure les sauts de ligne dans une entrée de commande

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class GreetingCommands {

    @ShellMethod("Hello World")
    public void hello(int a, int b, int c) {
        System.out.println("a=" + a + ", b=" + b + ", c=" + c);
    }
}

Résultat d'exécution


shell:>【hello \】
> 【--a 10 \】
> 【--b 20 \】
> 【--c 30】
a=10, b=20, c=30

Définition de la commande

SampleCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello Spring Shell!!");
    }
}

--Pour définir une commande, créez d'abord une classe arbitraire et annotez la classe avec @ ShellComponent.

  1. Phrases courtes (environ 1 ou 2 phrases)
  2. Commencez par une majuscule et terminez par un point

Spécifiez le nom de la commande

SampleCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod(value="Hello World", key="hoge")
    public void hello() {
        System.out.println("Hello Spring Shell!!");
    }
}

Résultat d'exécution


shell:>【hoge】
Hello Spring Shell!!

shell:>【hello】
No command found for 'hello'
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

Attribuer plusieurs noms

SampleCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod(value="Hello World", key={"hoge", "fuga"})
    public void hello() {
        System.out.println("Hello Spring Shell!!");
    }
}

Résultat d'exécution


shell:>【hoge】
Hello Spring Shell!!

shell:>【fuga】
Hello Spring Shell!!

shell:>【help】
AVAILABLE COMMANDS

Built-In Commands
        ...

Sample Commands
        fuga, hoge: Hello World

Spécification d'argument

python


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod("Hello World")
    public void hello(int a, int b, int c) {
        System.out.println("a=" + a + ", b=" + b + ", c=" + c);
    }
}

Résultat d'exécution


shell:>【hello 1 2 3】
a=1, b=2, c=3

shell:>【hello 1 2】
Parameter '--c int' should be specified
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

shell:>【hello a 2 3】
Failed to convert from type [java.lang.String] to type [int] for value 'a'; nested exception is java.lang.NumberFormatException: For input string: "a"
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

--Si vous définissez un argument pour une méthode, vous pouvez passer l'argument à la commande.

Donnez-lui un nom et passez l'argument

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod("Hello World")
    public void hello(int a, int b, int fooBar) {
        System.out.println("a=" + a + ", b=" + b + ", fooBar=" + fooBar);
    }
}

Résultat d'exécution


shell:>【hello --a 1 --b 2 --foo-bar 3】
a=1, b=2, fooBar=3

shell:>【hello --foo-bar 3 --a 1 --b 2】
a=1, b=2, fooBar=3

shell:>【hello --b 2 1 3】
a=1, b=2, fooBar=3

Changer le préfixe

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod(value="Hello World", prefix="-")
    public void hello(int a) {
        System.out.println("a=" + a);
    }
}

Résultat d'exécution


shell:>【hello -a 1】
a=1

Changer le nom de l'argument

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod("Hello World")
    public void hello(int a, @ShellOption("--foo") int b, @ShellOption({"-h", "--hoge"}) int c) {
        System.out.println("a=" + a + ", b=" + b + ", c=" + c);
    }
}

Résultat d'exécution


shell:>【hello --a 1 --foo 2 -h 3】
a=1, b=2, c=3

shell:>【hello --a 1 --foo 2 --hoge 3】
a=1, b=2, c=3

--Si vous annotez un argument de méthode avec @ ShellOption, vous pouvez changer le nom de l'argument de commande avec l'attribut valeur.

Valeur par défaut de l'argument

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

@ShellComponent
public class SampleCommands {
    
    @ShellMethod("Hello World")
    public void hello(@ShellOption(defaultValue="9") int a) {
        System.out.println("a=" + a);
    }
}

Résultat d'exécution


shell:>【hello】
a=9

shell:>【hello 1】
a=1

Recevez plusieurs valeurs avec un seul argument

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

import java.util.Arrays;

@ShellComponent
public class SampleCommands {

    @ShellMethod("Hello World")
    public void hello(@ShellOption(arity=3) int[] a, int b) {
        System.out.println("a=" + Arrays.toString(a) + ", b=" + b);
    }
}

Résultat d'exécution


shell:>【hello 1 2 3 4】
a=[1, 2, 3], b=4

shell:>【hello --a 1 2 3 --b 4】
a=[1, 2, 3], b=4

shell:>【hello 1 --b 4 2 3】
a=[1, 2, 3], b=4

shell:>【hello --a 1 2 --b 4】
Failed to convert from type [java.lang.String] to type [@org.springframework.shell.standard.ShellOption int] for value '--b'; nested exception is java.lang.NumberFormatException: For input string: "--b"
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

shell:>【hello --a 1 2 3 4 --b 5】
Too many arguments: the following could not be mapped to parameters: '4'
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

argument booléen

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {

    @ShellMethod("Hello World")
    public void hello(boolean a) {
        System.out.println("a=" + a);
    }
}

Résultat d'exécution


shell:>【hello】
a=false

shell:>【hello --a】
a=true

--Si le type d'argument est booléen, la méthode de spécification dans la commande change légèrement. --Si aucun argument de commande n'est spécifié, ce sera faux. --Lors de la spécification des arguments de commande, spécifiez uniquement le nom et ne transmettez pas de valeur (une erreur se produira si vous essayez de transmettre une valeur comme --a true) --Si vous spécifiez un argument, il devient «vrai» par lui-même.

Lorsqu'une valeur par défaut est spécifiée pour l'argument booléen

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

@ShellComponent
public class SampleCommands {

    @ShellMethod("Hello World")
    public void hello(@ShellOption(defaultValue="true") boolean a, @ShellOption(defaultValue="false") boolean b) {
        System.out.println("a=" + a + ", b=" + b);
    }
}

Résultat d'exécution


shell:>【hello】
a=true, b=false

shell:>【hello --a --b】
a=false, b=true

Utiliser la validation de bean

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

@ShellComponent
public class SampleCommands {

    @ShellMethod("Hello World")
    public void hello(@Min(0) @Max(100) int a) {
        System.out.println("a=" + a);
    }
}

Résultat d'exécution


shell:>【hello -1】
The following constraints were not met:
        --a int : must be greater than or equal to 0 (You passed '-1')

shell:>【hello 0】
a=0

shell:>【hello 100】
a=100

shell:>【hello 101】
The following constraints were not met:
        --a int : must be less than or equal to 100 (You passed '101')

--Spring Shell prend en charge la validation de bean, et la vérification d'entrée peut être effectuée en ajoutant des annotations de contrainte de validation de bean aux arguments de méthode.

Convertir en n'importe quel type

SampleCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {

    @ShellMethod("Hello World")
    public void hello(Hoge hoge) {
        hoge.hello();
    }
}

Hoge.java


package sample.spring.shell;

public class Hoge {
    
    private final String value;

    public Hoge(String value) {
        this.value = value;
    }
    
    public void hello() {
        System.out.println("Hoge(" + this.value + ")");
    }
}

HogeConverter.java


package sample.spring.shell;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class HogeConverter implements Converter<String, Hoge> {
    
    @Override
    public Hoge convert(String source) {
        return new Hoge(source);
    }
}

Résultat d'exécution


shell:>【hello Hey】
Hoge(Hey)

Activer / désactiver dynamiquement les commandes

package sample.spring.shell;

import org.springframework.shell.Availability;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    private boolean greeted;

    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello!!");
        this.greeted = true;
    }
    
    @ShellMethod("Good Bye")
    public void bye() {
        System.out.println("Bye!!");
    }
    
    public Availability byeAvailability() {
        return this.greeted
                ? Availability.available()
                : Availability.unavailable("you does not greet yet.");
    }
}

Résultat d'exécution


shell:>【bye】
Command 'bye' exists but is not currently available because you does not greet yet.
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

shell:>【help】
AVAILABLE COMMANDS

Built-In Commands
        ...

Sample Commands
      * bye: Good Bye
        hello: Hello World

Commands marked with (*) are currently unavailable.
Type `help <command>` to learn more.

shell:>【hello】
Hello!!

shell:>【bye】
Bye!!

Rendre arbitraire le nom de la méthode de jugement valide / invalide

package sample.spring.shell;

import org.springframework.shell.Availability;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellMethodAvailability;

@ShellComponent
public class SampleCommands {
    
    private boolean greeted;

    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello!!");
        this.greeted = true;
    }
    
    @ShellMethod("Good Bye")
    @ShellMethodAvailability("checkByeAvailability")
    public void bye() {
        System.out.println("Bye!!");
    }
    
    public Availability checkByeAvailability() {
        return this.greeted
                ? Availability.available()
                : Availability.unavailable("you does not greet yet.");
    }
}

Contrôlez la validité / l'invalidité de plusieurs commandes à la fois

package sample.spring.shell;

import org.springframework.shell.Availability;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellMethodAvailability;

@ShellComponent
public class SampleCommands {
    
    private boolean greeted;

    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello!!");
        this.greeted = true;
    }
    
    @ShellMethod("Good Bye")
    public void bye() {
        System.out.println("Bye!!");
    }
    
    @ShellMethod("lol")
    public void laugh() {
        System.out.println("HAHAHAHA!!");
    }
    
    @ShellMethodAvailability({"bye", "laugh"})
    public Availability checkAvailability() {
        return this.greeted
                ? Availability.available()
                : Availability.unavailable("you does not greet yet.");
    }
}

Résultat d'exécution


shell:>【laugh】
Command 'laugh' exists but is not currently available because you does not greet yet.
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

shell:>【bye】
Command 'bye' exists but is not currently available because you does not greet yet.
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

shell:>【hello】
Hello!!

shell:>【laugh】
HAHAHAHA!!

shell:>【bye】
Bye!!

Contrôle la validité / l'invalidité de toutes les commandes de la classe à la fois

SampleCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class SampleCommands {
    
    private boolean greeted;

    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello!!");
        this.greeted = true;
    }
    
    public boolean isGreeted() {
        return this.greeted;
    }
}

SomeCommands.java


package sample.spring.shell;

import org.springframework.shell.Availability;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellMethodAvailability;

@ShellComponent
public class SomeCommands {
    
    private final SampleCommands sampleCommands;

    public SomeCommands(SampleCommands sampleCommands) {
        this.sampleCommands = sampleCommands;
    }

    @ShellMethod("Good Bye")
    public void bye() {
        System.out.println("Bye!!");
    }

    @ShellMethod("lol")
    public void laugh() {
        System.out.println("HAHAHAHA!!");
    }

    @ShellMethodAvailability
    public Availability checkAvailability() {
        return this.sampleCommands.isGreeted()
                ? Availability.available()
                : Availability.unavailable("you does not greet yet.");
    }
}

Résultat d'exécution


shell:>【help】
AVAILABLE COMMANDS

Built-In Commands
        ...

Sample Commands
        hello: Hello World

Some Commands
      * bye: Good Bye
      * laugh: lol

Commands marked with (*) are currently unavailable.
Type `help <command>` to learn more.

Regroupement de commandes

Regroupement par défaut

GreetingCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class GreetingCommands {

    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello!!");
    }

    @ShellMethod("Good Bye")
    public void bye() {
        System.out.println("Bye!!");
    }
}

CalcCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class CalcCommands {
    
    @ShellMethod("a + b")
    public int add(int a, int b) {
        return a + b;
    }
    
    @ShellMethod("a - b")
    public int minus(int a, int b) {
        return a - b;
    }
}

Résultat d'exécution


shell:>【help】
AVAILABLE COMMANDS

Built-In Commands
        ...

Calc Commands
        add: a + b
        minus: a - b

Greeting Commands
        bye: Good Bye
        hello: Hello World

--Si vous ne spécifiez pas de groupe, un groupe est défini pour chaque classe annotée avec @ ShellComponent, et les commandes qui y sont définies sont affectées au groupe correspondant à cette classe.

Spécifiez un groupe pour chaque commande

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class GreetingCommands {

    @ShellMethod(value="Hello World", group="Hello")
    public void hello() {
        System.out.println("Hello!!");
    }

    @ShellMethod("Good Bye")
    public void bye() {
        System.out.println("Bye!!");
    }
}

Résultat d'exécution


shell:>【help】
AVAILABLE COMMANDS

Built-In Commands
        ...

Greeting Commands
        bye: Good Bye

Hello
        hello: Hello World

--Si vous spécifiez le nom du groupe dans l'attribut groupe de @ ShellMethod, vous pouvez spécifier le groupe pour chaque commande.

Spécifiez un groupe pour chaque classe

GreetingCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellCommandGroup;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
@ShellCommandGroup("My Commands")
public class GreetingCommands {

    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello!!");
    }

    @ShellMethod("Good Bye")
    public void bye() {
        System.out.println("Bye!!");
    }
}

CalcCommands.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellCommandGroup;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
@ShellCommandGroup("My Commands")
public class CalcCommands {
    
    @ShellMethod("a + b")
    public int add(int a, int b) {
        return a + b;
    }
    
    @ShellMethod("a - b")
    public int minus(int a, int b) {
        return a - b;
    }
}

Résultat d'exécution


shell:>【help】
AVAILABLE COMMANDS

Built-In Commands
        ...

My Commands
        add: a + b
        bye: Good Bye
        hello: Hello World
        minus: a - b

--Annotez la classe qui définit la commande avec @ ShellCommandGroup

Spécifiez un groupe pour chaque package

package-info.java


@ShellCommandGroup("my commands")
package sample.spring.shell;

import org.springframework.shell.standard.ShellCommandGroup;

Résultat d'exécution


shell:>【help】
AVAILABLE COMMANDS

Built-In Commands
        ...

my commands
        add: a + b
        bye: Good Bye
        hello: Hello World
        minus: a - b

--Créez package-info.java et annotez le package avec @ ShellCommandGroup

Voir l'aide sur les commandes

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

@ShellComponent
public class GreetingCommands {

    @ShellMethod(value="Hello World")
    public void hello(int a, @ShellOption(defaultValue="9", help="help text") int b) {
        System.out.println("Hello!!");
    }
}

Résultat d'exécution


shell:>【help hello】


NAME
        hello - Hello World

SYNOPSYS
        hello [--a] int  [[--b] int]

OPTIONS
        --a  int

                [Mandatory]

        --b  int
                help text
                [Optional, default = 9]

Changer l'invite

package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
public class GreetingCommands {
    
    private boolean greeted;

    @ShellMethod("Hello World")
    public void hello() {
        System.out.println("Hello!!");
        this.greeted = true;
    }

    @ShellMethod("Good Bye")
    public void bye() {
        System.out.println("Bye!!");
    }

    public boolean isGreeted() {
        return greeted;
    }
}

MyPromptProvider.java


package sample.spring.shell;

import org.jline.utils.AttributedString;
import org.jline.utils.AttributedStyle;
import org.springframework.shell.jline.PromptProvider;
import org.springframework.stereotype.Component;

@Component
public class MyPromptProvider implements PromptProvider {
    
    private final GreetingCommands greetingCommands;

    public MyPromptProvider(GreetingCommands greetingCommands) {
        this.greetingCommands = greetingCommands;
    }

    @Override
    public AttributedString getPrompt() {
        return this.greetingCommands.isGreeted()
                ? new AttributedString("greeted > ", AttributedStyle.DEFAULT.foreground(AttributedStyle.WHITE))
                : new AttributedString("not greeted > ", AttributedStyle.DEFAULT.foreground(AttributedStyle.RED));
    }
}

Résultat d'exécution


not greeted > 【hello】
Hello!!

greeted >

Personnalisation des commandes intégrées

Désactiver les commandes intégrées

build.gradle


dependencies {
	compile('org.springframework.shell:spring-shell-starter:2.0.0.RELEASE') {
		exclude module: 'spring-shell-standard-commands'
	}
}

Résultat d'exécution


shell:>【help】
No command found for 'help'

Désactiver uniquement des commandes spécifiques

package sample.spring.shell;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.StringUtils;

@SpringBootApplication
public class SampleApplication {

	public static void main(String[] args) {
		String[] disabledCommands = {"--spring.shell.command.help.enabled=false"};
		String[] fullArgs = StringUtils.concatenateStringArrays(args, disabledCommands);
		SpringApplication.run(SampleApplication.class, fullArgs);
	}
}

Résultat d'exécution


shell:>【help】
No command found for 'help'
Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.

shell:>【stacktrace】
org.springframework.shell.CommandNotFound: No command found for 'help'
        at org.springframework.shell.Shell.evaluate(Shell.java:180)
        at org.springframework.shell.Shell.run(Shell.java:134)
        ...

Remplacer le comportement des commandes intégrées

SampleApplication.java


package sample.spring.shell;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.StringUtils;

@SpringBootApplication
public class SampleApplication {

	public static void main(String[] args) {
		String[] disabledCommands = {"--spring.shell.command.help.enabled=false"};
		String[] fullArgs = StringUtils.concatenateStringArrays(args, disabledCommands);
		SpringApplication.run(SampleApplication.class, fullArgs);
	}
}

MyHelpCommand.java


package sample.spring.shell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.commands.Help;

@ShellComponent
public class MyHelpCommand implements Help.Command {
    
    @ShellMethod("My help command.")
    public void help() {
        System.out.println("HELP ME!!!!");
    }
}

Résultat d'exécution


shell:>【help】
HELP ME!!!!
  1. Désactivez la commande intégrée que vous souhaitez écraser
  2. Définissez votre propre commande avec le même nom

référence

Recommended Posts

Notes d'utilisation de Spring Shell
Mémo d'utilisation de Spring Security CSRF
Mémo d'utilisation de Spring Security Run-As
Spring Security Usage Memo Method Security
Mémo d'utilisation de Spring Security Remember-Me
Mémo d'utilisation de Spring Security CORS
Test de mémo d'utilisation de Spring Security
En-tête de réponse de mémo d'utilisation de Spring Security
Gestion des sessions de mémo d'utilisation de Spring Security
Mémo d'utilisation de Spring Security Basic / mécanisme
Mémo rétrospective du printemps
Notes d'utilisation de JavaParser
Notes d'utilisation de WatchService
Mémo d'utilisation PlantUML
Notes d'utilisation de JUnit5
Spring Security Usage Memo Domain Object Security (ACL)
Rédaction de mémo de démarrage de printemps (1)
Rédaction de mémos de démarrage de printemps (2)
Mémo d'utilisation de Spring Security: coopération avec Spring MVC et Boot
[Notes personnelles] À propos du framework Spring
Mémo de participation au printemps JJUG CCC 2018
Série de mémos d'auto-apprentissage Spring Framework_1
Notes sur l'utilisation du plug-in de gestion des dépendances
Mémo de méthode de contrôleur de démarrage à ressort
Mémo d'utilisation de JCA (Java Encryption Architecture)
cadre de printemps Mémo d'étude simple (2): AOP
Mémo après le premier projet Spring-MVC-
Un mémo qui a touché Spring Boot
Mémo de mise à niveau de la version d'introduction approfondie du printemps
Mémo après le premier projet Spring-Database-
Comment utiliser Thymeleaf avec Spring Boot
Mémo généré automatiquement par swagger condegen (spring) -1
Mémo de construction de l'environnement Spring Boot sur Mac
Mémo après le premier projet Spring-What is Spring-
Spring Boot + Thymeleaf Boot Strap Méthode d'installation mémo