Sunday, 31 January 2021

Spring Shell: Named Parameters

You can execute the command by specifying a parameter name while executing.

 

Example

@ShellComponent(value = "Named Parameters Demo")
public class NamedParams {
    @ShellMethod(value = "Commands to print User Details", key = "get-user")
    public String printUserDetails(String name, int age, String city) {

        StringBuilder builder = new StringBuilder();

        builder.append("Hello ").append(name).append("!!!!").append(". You are ").append(age)
                .append(" years old and you are from ").append(city);

        return builder.toString();
    }
}

 

Using positional parameters, you can call the command ‘get-user’ like below.

get-user "Krishna" 29 "Bangalore"

 

You can call the above command using named parameters like below.

get-user --name "Krishna" --age 29 --city "Bangalore"

 

As you see above command, I executed the command using a parameter key (e.g. --arg value).

 

Named parameters can be reordered as desired.

get-user --age 29  --city "Bangalore" --name "Krishna"

 

You can even mix both named and positional parameters. The non by-name parameters are resolved in the order they appear

 

get-user --age 29 "Krishna" "Bangalore"

get-user "Krishna" "Bangalore" --age 29

 

shell:>get-user "Krishna" 29 "Bangalore"
Hello Krishna!!!!. You are 29 years old and you are from Bangalore
shell:>
shell:>get-user --name "Krishna" --age 29 --city "Bangalore"
Hello Krishna!!!!. You are 29 years old and you are from Bangalore
shell:>
shell:>get-user --age 29  --city "Bangalore" --name "Krishna"
Hello Krishna!!!!. You are 29 years old and you are from Bangalore
shell:>
shell:>get-user --age 29 "Krishna" "Bangalore" 
Hello Krishna!!!!. You are 29 years old and you are from Bangalore
shell:>
shell:>get-user "Krishna" "Bangalore" --age 29 
Hello Krishna!!!!. You are 29 years old and you are from Bangalore

 

You can download complete application from this link.

https://github.com/harikrishna553/springboot/tree/master/shell/hello-world

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment