diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java index 4c0134769..ed5f61435 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java @@ -48,6 +48,7 @@ import org.springframework.util.Assert; * @author Dave Syer * @author Michael Minella * @author Mahmoud Ben Hassine + * @author Nicolas Widart * */ public class StepContext extends SynchronizedAttributeAccessor { @@ -101,6 +102,19 @@ public class StepContext extends SynchronizedAttributeAccessor { return stepExecution.getJobExecution().getJobInstance().getJobName(); } + /** + * Convenient accessor for current job identifier. + * + * @return the job identifier of the enclosing {@link JobInstance} + * associated with the current {@link StepExecution} + */ + public Long getJobId() { + Assert.state(stepExecution.getJobExecution() != null, "StepExecution does not have a JobExecution"); + Assert.state(stepExecution.getJobExecution().getJobInstance() != null, + "StepExecution does not have a JobInstance"); + return stepExecution.getJobExecution().getJobInstance().getId(); + } + /** * Convenient accessor for System properties to make it easy to access them * from placeholder expressions. diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java index e2f209cf7..8628512d1 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2014 the original author or authors. + * Copyright 2006-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ import org.springframework.batch.item.ExecutionContext; /** * @author Dave Syer + * @author Nicolas Widart * */ public class StepContextTests { @@ -164,6 +165,11 @@ public class StepContextTests { assertEquals("job", context.getJobName()); } + @Test + public void testJobId() throws Exception { + assertEquals(2L, (long)context.getJobId()); + } + @Test public void testStepExecutionContext() throws Exception { ExecutionContext executionContext = stepExecution.getExecutionContext();