skip to content

How are JobParameters validated and converted, and how would you enforce required parameters?

level: seniorimportance: nice to knowfreq 30%

answer

  1. JobBuilder.validator(...) runs pre-launch
  2. DefaultJobParametersValidator = required/optional keys only
  3. throw JobParametersInvalidException
  4. CompositeJobParametersValidator to combine
  5. Batch 5 converter uses ConversionService

basics

~10 s

Attach a JobParametersValidator to the job (DefaultJobParametersValidator for required/optional key checks, or a custom one) to fail fast on bad input. Conversion from string form uses a JobParametersConverter / ConversionService in Spring Batch 5.

solid answer

~40 s

A job can declare a JobParametersValidator via JobBuilder.validator(...). Spring Batch invokes it before the job runs and aborts with JobParametersInvalidException if it fails. The built-in DefaultJobParametersValidator lets you declare requiredKeys and optionalKeys — it errors if a required key is missing or an unexpected key appears. For richer rules (ranges, formats, mutually-exclusive flags) you implement JobParametersValidator.validate(JobParameters) and throw JobParametersInvalidException yourself, or compose several with CompositeJobParametersValidator. On conversion: when parameters arrive as strings (CLI, REST), Spring Batch 5 uses a JobParametersConverter (DefaultJobParametersConverter backed by a ConversionService) to turn typed literals into JobParameter<T> values, replacing the older suffix-based string encoding. This is why typing matters — validation and identity both rely on the correct converted type.

code

java · 22 lines
java
@Bean
Job ordersJob(JobRepository repo, Step step) {
    var presence = new DefaultJobParametersValidator(
        new String[] { "inputFile", "businessDate" },  // required
        new String[] { "triggeredBy" });                // optional (allow-list)

    var composite = new CompositeJobParametersValidator();
    composite.setValidators(List.of(presence, new BusinessDateValidator()));

    return new JobBuilder("ordersJob", repo)
        .validator(composite)   // runs before the job; throws JobParametersInvalidException on failure
        .start(step)
        .build();
}

class BusinessDateValidator implements JobParametersValidator {
    public void validate(JobParameters p) throws JobParametersInvalidException {
        LocalDate d = p.getLocalDate("businessDate");
        if (d == null || d.isAfter(LocalDate.now()))
            throw new JobParametersInvalidException("businessDate must be <= today");
    }
}

go deeper

for a junior

Know a validator can require certain parameters and fail fast.

for a middle

Use DefaultJobParametersValidator required/optional keys and wire via .validator().

for a senior

Build custom/composite validators and explain conversion via JobParametersConverter/ConversionService.

for a principal

Standardize parameter contracts, type converters, and validation across many jobs; handle Batch 4->5 converter migration.

## Validation Spring Batch runs an optional **`JobParametersValidator`** *before* launching the job. Interface: ```java public interface JobParametersValidator { void validate(JobParameters parameters) throws JobParametersInvalidException; } ``` If `validate` throws `JobParametersInvalidException`, the job does **not** start. You attach it on the builder: ```java new JobBuilder("ordersJob", repo) .validator(myValidator) .start(step) .build(); ``` ### DefaultJobParametersValidator The stock implementation, `org.springframework.batch.core.job.DefaultJobParametersValidator`, checks presence: ```java DefaultJobParametersValidator v = new DefaultJobParametersValidator( new String[] { "inputFile", "businessDate" }, // requiredKeys new String[] { "triggeredBy" }); // optionalKeys ``` - If a **required** key is missing → invalid. - If a key appears that is neither required nor optional → invalid (when optional keys are specified, the set is treated as an allow-list). It does **not** validate values (ranges, formats) — only key presence. ### Custom and composite validators For value-level rules (date not in the future, amount > 0, exactly one of flag A/B), implement `JobParametersValidator` directly and throw `JobParametersInvalidException` with a message. To combine several, use `CompositeJobParametersValidator`, which runs a list of validators in order. ```java class BusinessDateValidator implements JobParametersValidator { public void validate(JobParameters p) throws JobParametersInvalidException { LocalDate d = p.getLocalDate("businessDate"); if (d == null || d.isAfter(LocalDate.now())) throw new JobParametersInvalidException("businessDate must be today or earlier"); } } ``` ## Conversion Parameters often originate as **strings** — command line (`businessDate=2026-07-01`), a REST payload, or a scheduler. Spring Batch converts these into typed `JobParameter<T>` values. - **`JobParametersConverter`** (interface) converts between a `Properties`/string form and `JobParameters`. The default is **`DefaultJobParametersConverter`**. - In **Spring Batch 5**, `DefaultJobParametersConverter` delegates to a Spring **`ConversionService`**, so any type with a registered converter is supported; the legacy type-suffix syntax (e.g., `run.id(long)=1`) was superseded by a cleaner `value,type,identifying` form. You can register custom `Converter`s for domain types. Accessing typed values back out: `getString`, `getLong`, `getDate`, `getLocalDate`, etc., on `JobParameters`. ## Why it all connects Typing + conversion feed **identity** (the identifying-parameter hash is type-aware) and **validation** (you validate the converted value). Getting the type wrong (`"1"` String vs `1L` Long) yields a *different* `JobInstance` and can slip past a presence-only validator. ## Gotchas - `DefaultJobParametersValidator` only checks keys, not values — don't assume it range-checks. - Validation runs before the first step; a failure means zero steps execute and no meaningful `JobExecution` work is done. - If you specify only `requiredKeys` and leave `optionalKeys` empty, extra keys are permitted; specifying `optionalKeys` turns it into an allow-list. - Converter differences between Batch 4 and 5 are a frequent migration snag.

  • Does DefaultJobParametersValidator check parameter values like ranges or formats?
    No. It only verifies key presence — required keys are present and, if optional keys are declared, no unexpected keys appear. Value-level rules need a custom JobParametersValidator, optionally combined via CompositeJobParametersValidator.
  • When does the validator run and what happens on failure?
    Before the job's first step. On failure it throws JobParametersInvalidException and the job does not start, so no steps execute.

  • Thinking DefaultJobParametersValidator validates values, not just keys
  • Assuming validation runs after steps start
  • Not knowing Spring Batch 5 conversion goes through a ConversionService

context