Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Validate every argument before opening files, contacting services, or launching subprocesses. For configuration-like options, bind a dedicated prefix such as cli to a typed @ConfigurationProperties class and apply Bean Validation. For positional arguments, subcommands, duplicate-option rules, or strict CLI syntax, parse ApplicationArguments explicitly. Neither approach makes operating-system command execution safe by itself.

How Spring Boot interprets command-line arguments

By default, Spring Boot adds arguments beginning with -- to the application Environment as command-line properties. These properties take precedence over file-based configuration, so an invocation such as java -jar app.jar --server.port=9090 can override a configured server port. See Spring Boot externalized configuration.

ApplicationArguments provides a structured view of the original arguments:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • getSourceArgs() returns the raw argument array.
  • getOptionNames() returns option names, such as foo for --foo=bar.
  • containsOption("foo") checks whether an option was supplied.
  • getOptionValues("foo") returns null when absent, an empty list for a flag such as --foo, and one or more values for valued or repeated options.
  • getNonOptionArgs() returns positional arguments.

These distinctions matter: an absent value, a bare flag, and --name= are not the same input. Define the accepted spelling, whether repetition is allowed, how flags work, and what -- means for your CLI. See the ApplicationArguments API.

#1 Best Overall
Gogoonike Adjustable Laptop Stand for Desk, Metal Laptop Riser Holder
  • 【Adjustable & Ergonomic】:This laptop stand can be adjusted to a comfortable height and angle according to your actual needs, letting you fix posture and reduce your neck fatigue, back pain and eye strain. Very comfortable for working in home, office and outdoor.
  • 【Sturdy & Protective】 :Made of sturdy metal, it can support up to 17.6 lbs (8kg) weight on top; With 2 rubber mats on the hook and anti-skid silicone pads on top & bottom, it can secure your laptop in place and maximum protect your device from scratches and sliding. Moreover, smooth edges will never hurt your hands.
  • 【Heat Dissipation】 :The top of the laptop stand is designed with multiple ventilation holes. The open design offers greater ventilation and more airflow to cool your laptop during operation other than it just lays flat on the table.
  • 【Portable & Foldable】:The foldable design allows you to easily slip it in your backpack. Ideal for people who travel for business a lot.
  • 【Broad Compatibility】:Our desktop book stand is compatible with all laptops from 10-15.6 inches, such as MacBook Air/ Pro, Google Pixelbook, Dell XPS, HP, ASUS, Lenovo ThinkPad, Acer, Chromebook and Microsoft Surface, etc.Be your ideal companion in Home, Office & Outdoor.

Choose a parsing model that matches the interface

Approach Best suited to Trade-off
@ConfigurationProperties with @Validated Typed, configuration-like options with ranges, patterns, and defaults. Does not define a complete CLI grammar; global unknown options require separate checks.
ApplicationRunner with ApplicationArguments Positional arguments, subcommands, and explicit presence or repetition rules. You own parsing, validation, and error messages.
CommandLineRunner Small tools that only need raw String... arguments. It lacks the structured option API, so manual parsing is easier to get wrong.
A dedicated CLI parser Rich grammar, aliases, generated help, or extensive subcommands. Adds a dependency and integration work.
Manual Environment or @Value injection One or two simple properties. Scatters rules and offers fewer structured binding and validation features.

Spring Boot documents @ConfigurationProperties as the type-safe, structured alternative to scattered @Value injection. For a CLI with a formal grammar, treat arguments as a CLI interface rather than assuming configuration binding supplies parsing, help, or positional-argument rules.

Bind and validate configuration-style options

Reserve an application-specific prefix and keep its contract in one typed class. The example below requires an operation, constrains its spelling, bounds a count, and limits an input string’s length:

package com.example.demo;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

@ConfigurationProperties(prefix = "cli", ignoreUnknownFields = false)
@Validated
public record CliOptions(
        @NotBlank
        @Pattern(regexp = "[a-z0-9-]{1,32}")
        String operation,

        @NotNull
        @Min(1)
        @Max(1000)
        Integer count,

        @Size(max = 4096)
        String input) {
}

Register configuration-properties scanning on the application:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
@SpringBootApplication
@ConfigurationPropertiesScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Add the validation starter so Bean Validation is available:

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

Then invoke the application with options under the prefix:

Rank #2
WOLFBOX MegaFlow 50 Compressed Air Duster, 110,000 RPM, 3-Gear Adjustable
  • Powerful Turbo Fan:WOLFBOX MegaFlow 50 electric air duster reaches speeds of up to 110,000 RPM, effectively removing dust and debris. It features three adjustable speed settings to suit different cleaning tasks.
  • Economical and Reusable: Built from durable materials with a long-lasting battery, the WOLFBOX MegaFlow 50 is a sustainable alternative to disposable air cans, enhancing your cleaning experience.
  • Portable and Lightweight: Weighing only 0.45 lb, this compact air duster is easy to carry. The included lanyard ensures convenient use both indoors and outdoors.
  • Wide Application: WOLFBOX MegaFlow 50 electric air duster comes with 4 nozzles, making it suitable for a variety of scenes, such as pc, keyboards, or other electronic devices. It also serves well for home clean and car duster.
  • 3.5 Hours Fast Charging: WOLFBOX MegaFlow 50 electric air duster recharges in just 3.5 hours with a type-C cable. Enjoy up to 240 minutes of use on the lowest setting, with four charging options to suit your needs.To ensure optimal performance of your MF50, please fully charge the battery before use.
java -jar app.jar \
  --cli.operation=import \
  --cli.count=10 \
  --cli.input=/work/data.csv

Spring Boot validates a configuration-properties type annotated with @Validated. Nested objects need @Valid for cascaded validation. Unknown properties are ignored by default, so ignoreUnknownFields=false makes undeclared properties under this bound prefix fail binding. Invalid type conversion is not ignored by default. These settings apply to the bound properties object, not every option supplied to the process. See the externalized configuration reference and ConfigurationProperties API.

The example uses jakarta.validation. Spring Boot 2 applications generally use javax.validation; check the imports against the application’s Boot major version. See the Spring Boot 3 migration guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reject options outside the declared CLI contract

Strict binding of cli.* does not reject an unrelated option such as --clii.count=10. Inspect option names and compare them with the complete set the application intends to accept:

private static final Set<String> ALLOWED = Set.of(
        "cli.operation",
        "cli.count",
        "cli.input",
        "help"
);

static void rejectUnknown(ApplicationArguments args) {
    List<String> unknown = args.getOptionNames().stream()
            .filter(name -> !ALLOWED.contains(name))
            .sorted()
            .toList();

    if (!unknown.isEmpty()) {
        throw new IllegalArgumentException(
                "Unknown option(s): " + unknown);
    }
}

Decide explicitly whether Spring options such as --debug belong to the public contract. If an option may repeat, define whether all values are accepted, exactly one is required, or repetition is an error; do not silently take the first value.

If the application must not expose arbitrary command-line options as Spring configuration, disable the command-line property source:

Rank #3
Sale
Acer USB Hub 4 Ports, Multiple USB 3.0 Hub, USBA Splitter for Laptop/PC 2FT
  • 【4 Ports USB 3.0 Hub】Acer USB Hub extends your device with 4 additional USB 3.0 ports, ideal for connecting USB peripherals such as flash drive, mouse, keyboard, printer
  • 【5Gbps Data Transfer】The USB splitter is designed with 4 USB 3.0 data ports, you can transfer movies, photos, and files in seconds at speed up to 5Gbps. When connecting hard drives to transfer files, you need to power the hub through the 5V USB C port to ensure stable and fast data transmission
  • 【Excellent Technical Design】Build-in advanced GL3510 chip with good thermal design, keeping your devices and data safe. Plug and play, no driver needed, supporting 4 ports to work simultaneously to improve your work efficiency
  • 【Portable Design】Acer multiport USB adapter is slim and lightweight with a 2ft cable, making it easy to put into bag or briefcase with your laptop while traveling and business trips. LED light can clearly tell you whether it works or not
  • 【Wide Compatibility】Crafted with a high-quality housing for enhanced durability and heat dissipation, this USB-A expansion is compatible with Acer, XPS, PS4, Xbox, Laptops, and works on macOS, Windows, ChromeOS, Linux
public static void main(String[] args) {
    SpringApplication application = new SpringApplication(Application.class);
    application.setAddCommandLineProperties(false);
    application.run(args);
}

With that setting, configuration properties no longer receive command-line values automatically. Parse ApplicationArguments yourself and map only approved values into the application model. See the SpringApplication API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Parse positional arguments and subcommands explicitly

Use ApplicationArguments when the interface includes a command word or positional values. Validate the complete shape before dispatching to business operations:

@Bean
ApplicationRunner explicitCli() {
    return args -> {
        rejectUnknown(args);

        List<String> positional = args.getNonOptionArgs();
        if (positional.isEmpty()) {
            throw new IllegalArgumentException(
                    "Usage: app <command> [arguments]");
        }

        String command = positional.getFirst();
        switch (command) {
            case "import" -> validateImport(positional);
            case "export" -> validateExport(positional);
            default -> throw new IllegalArgumentException(
                    "Unknown command: " + command);
        }
    };
}

Convert values narrowly and report the expected format and range. Never turn malformed input into zero or a default:

static int parsePositiveInt(String value, String option) {
    try {
        int parsed = Integer.parseInt(value);
        if (parsed < 1 || parsed > 1000) {
            throw new IllegalArgumentException(
                    option + " must be between 1 and 1000");
        }
        return parsed;
    }
    catch (NumberFormatException ex) {
        throw new IllegalArgumentException(
                option + " must be a decimal integer", ex);
    }
}

For a one-shot command, document the exact invocation used in automation. Passing arguments through mvn spring-boot:run has Maven-plugin-specific handling; see the Spring Boot Maven run goal.

Finish validation before business work begins

ApplicationRunner and CommandLineRunner execute after the application context starts but before SpringApplication.run(...) completes and before Boot considers the application ready. A validation failure in a runner therefore prevents normal readiness. It does not undo infrastructure that may already have initialized during context startup, so validate as early as the architecture permits. Spring Boot recommends runners for startup tasks rather than using @PostConstruct; see the SpringApplication reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
OPNICE Desk Organizer and Accessories, 2-Tier Computer Monitor Stand Riser with Drawer and 2 Pen Holders, Laptop Stand, Office Desk Accessories for Office Supplies, Black
  • 【Ergonomic Design】:OPNICE newly releases the monitor stand for desk organizer! This computer stand elevates your monitor or laptop to a comfortable viewing height, relieving pressure on your neck, shoulders. Ideal for strengthening office organization and increasing comfort levels
  • 【Save Space】:This 2-Tier monitor stand with drawer and 2 hanging pen holders provides ample storage space to keep your office supplies and office desk accessories neatly organized and easily accessible, keeping your workspace tidy and improving your sense of well-being
  • 【Durable and Stable】:The metal computer stand is made of high quality material with sturdy construction, it can easily carry the weight of the display and computer accessories, to ensure stable and non-shaking for a long time, ideal for use in the office, dorm room or home
  • 【Sleek and Aesthetic】:This desktop organizer features a modern minimalist design that blends seamlessly with any office decor. It not only enhances functionality but also adds a touch of style and aesthetic to your workspace, making it an essential piece for your office organization efforts
  • 【Hassle-free Shopping】:OPNICE is committed to providing excellent after-sales service and offers a 100-day unconditional return policy for desk organizers and accessories. Comes with four non-slip pads that are height-adjustable to protect your table from scratches(U.S. Patent Pending)

Put cross-field and domain checks in a class-level constraint or an explicit preflight step. Complete all checks before opening files, connecting to databases, calling network clients, or starting subprocesses. Examples include:

  • Require --cli.input for an import operation.
  • Require a start date to precede an end date.
  • Reject incompatible options, such as JSON output combined with a binary mode.
  • Require exactly one of a file input and standard input.
  • Resolve a path against an approved root and check the resolved target against filesystem policy.
  • Cap requested concurrency at an operational limit.

Bean Validation checks declared constraints; it does not establish that a path is authorized, a URL is reachable, or a requested operation is safe. A normalized path may still escape through a symlink, so enforce filesystem policy at the point of use.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep subprocess execution safe

Arguments from scripts, schedulers, containers, or administrators are still untrusted. Avoid building a shell command by concatenating input. Prefer not to invoke an operating-system command at all; when it is necessary, use a fixed executable, a parameterized argument list, an allowlist, and least privilege:

List<String> command = List.of(
        "/usr/bin/tool",
        "--safe-mode",
        "--",
        validatedPath.toString());

Process process = new ProcessBuilder(command)
        .redirectErrorStream(true)
        .start();

Use -- only if the invoked program supports it; it commonly marks the end of option parsing so a user-controlled path cannot be interpreted as a new flag. Shell metacharacter filtering alone is not sufficient. OWASP distinguishes shell command injection from argument injection: an input may become a dangerous option even if it cannot start another shell command. Follow the OWASP OS Command Injection Defense Cheat Sheet and MITRE CWE-78 guidance on allowlisting and isolation.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not place passwords, tokens, or private keys in arguments when avoidable. Process inspection, supervisors, crash reports, and diagnostics may expose them; use an appropriate secret store or protected mounted file instead.

Best Value
Office Desk Accessories 2pcs Computer Monitor Memo Board Office Supplies
  • [MULTIFUNCTIONAL]You'll get 2 pieces computer monitor memo boards that you can stick on the left and right edges of your monitor, and they're the perfect office desk organizers and accessories. Computer monitor side panels desktop organizer are suitable for home work or office,bringing convenience. Desktop memo is used to organize meeting memos, important messages, business cards, planning notes.Paste on the message board to keep track of important things and to-do items to prevent forgetting.
  • [🌟HIGHLY QUALITY] The material of computer screen side note holder is transparent acrylic. Durable, simple, stylish, light weight, easy to use, not easy to fall off or break. This cute office supplies for women desk can be used for a long time. This computer desk accessories is waterproof and dirt resistance, and look simple and stylish. The transparent acrylic sticky note holder as cubicle accessories is easy to notice the context of your sticky notes.
  • [📋Easy to use] Office must haves cool office gadgets for desk ready to tear, easy to install and remove, not easy to leave traces. You only need to peel off the protective film on the surface of the computer side board memo, wipe off the dust on the edge of the computer monitor, and then stick the desk essentials for women office on the right or left side of the tape, and you're done. A perfect gift for your colleagues, friends or classmates and family members or relatives
  • [🏢MULTI-SCENE USE] This desk supplies computer memo board can be applied to home and office, clear your office decor for women, suitable for most computer monitors, screens and cabinets, you can put it where you think, this cute office decor serve as a reminder. Stick on the computer side. It’s a good office gadgets can remind work improve office productivity. Pasted cabinets, dressers, refrigerators, walls, etc as cubicle accessories. To make life more orderly.
  • [💌NOTE] The adhesive force of the computer sticky note holder is very strong. It can not be directly pasted on the computer screen. It should pasted on the black edge of the screen. Narrow edge not recommended!!! If you are not satisfied with your purchase, or if the product is damaged or broken in transit, please let us know immediately. We will promptly solve your problem.

Make failures useful to people and automation

Return a non-zero status for invalid input and make the message actionable without echoing secrets or dumping the raw argument array. Keep error categories distinct where callers need to respond differently:

  • Usage or validation error.
  • Authentication or authorization failure.
  • Input file or network failure.
  • Internal failure.

For example: Invalid --cli.count: expected an integer from 1 through 1000. Spring Boot provides startup failure analyzers and supports ExitCodeGenerator; the exit-code number is the application’s contract, not a universal Spring Boot value. See the startup failure and exit documentation and ExitCodeGenerator API.

A small wrapper can choose a documented usage-error code, for example 2, but that convention is yours to define:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
public static void main(String[] args) {
    try {
        SpringApplication.run(Application.class, args);
    }
    catch (RuntimeException ex) {
        System.err.println(ex.getMessage());
        System.exit(2);
    }
}

For a managed shutdown path, Spring Boot also supports SpringApplication.exit(...) with an ExitCodeGenerator; pass the resulting code to System.exit as documented in the SpringApplication reference.

Test the input contract and failure boundary

Test that invalid input fails before any operation with side effects, not just that a constraint throws. A useful test set includes:

  • A valid invocation and each documented default.
  • Missing required values, a bare flag, and an empty assignment such as --cli.operation=.
  • Malformed numbers, values at and beyond each bound, and overflow.
  • Repeated options and unknown names both inside and outside the cli prefix.
  • Positional arguments with missing, extra, or reordered values; unknown subcommands; and the documented behavior of --.
  • Cross-field conflicts and paths that traverse outside the approved root, including symlink cases where relevant.
  • Hostile subprocess values that resemble shell syntax or options, verifying they remain one data argument and cannot change the invoked tool’s behavior.
  • Exit status and error output, including confirmation that secrets and the raw argument list are not printed.

Also check resource limits on string lengths, list sizes, file sizes, and numeric inputs; define explicit locale and format rules for dates or decimals; and restrict or normalize identifiers where Unicode lookalikes could change authorization or routing. Lazy initialization may defer unrelated configuration failures, so do not rely on it as an argument-safety mechanism. If several runners exist, order validation ahead of runners that perform work using @Order or Ordered.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.