JobParametersValidator.validate() method parameters returns null in spring batch - spring

I am writing simple helloworld application in spring batch, and I'm trying to validate the JobParameters with custom implementation of JobParametersValidator.
public class ParameterValidator implements JobParametersValidator{
#Override
public void validate(JobParameters parameters) throws JobParametersInvalidException {
//String parameter = parameters.getParameters().get("outputText");
System.out.println("jobparameters are ............ " + parameters);
//System.out.println("parameter is " + parameter);
//if(!StringUtils.hasText(parameter)) {
throw new JobParametersInvalidException("Parameter is missing.........");
//}
}
}
But when I tried to Sysout the JobParameters inside the validate method, parameters return null.
Here is my console out.
2021-11-26 10:06:32.457 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : Starting SpringBatchDemo2Application using Java 16.0.2 on DESKTOP-T1L7IA7 with PID 11912 (D:\Workspace\EclipseWorkspaceSpringPractise\SpringBatchDemo2\target\classes started by arepa in D:\Workspace\EclipseWorkspaceSpringPractise\SpringBatchDemo2)
2021-11-26 10:06:32.458 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : No active profile set, falling back to default profiles: default
2021-11-26 10:06:32.536 INFO 11912 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-11-26 10:06:33.575 INFO 11912 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-11-26 10:06:33.784 INFO 11912 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-11-26 10:06:33.920 INFO 11912 --- [ restartedMain] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: POSTGRES
2021-11-26 10:06:34.262 INFO 11912 --- [ restartedMain] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2021-11-26 10:06:34.484 INFO 11912 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-11-26 10:06:34.539 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : Started SpringBatchDemo2Application in 2.596 seconds (JVM running for 4.056)
2021-11-26 10:06:34.544 INFO 11912 --- [ restartedMain] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
jobparameters are ............ {}
2021-11-26 10:06:34.713 INFO 11912 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-26 10:06:34.756 ERROR 11912 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
Here is my Job creation code.
#Component
public class HelloWorldJob {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
public Step step() {
Tasklet tasklet = (contribution, chunkContext) -> {
return RepeatStatus.FINISHED;
};
return this.stepBuilderFactory.get("step1")
.tasklet(tasklet).build();
}
#Bean
public Job job() {
return this.jobBuilderFactory.get("job1").start(step()).validator(new ParameterValidator()).build();
}
}
Here is my code for triggering jobs.
#Component
public class TriggerJobLauncher {
#Autowired
private JobLauncher launcher;
#Autowired
private Job job;
public void triggerJob() throws JobExecutionAlreadyRunningException,
JobRestartException,
JobInstanceAlreadyCompleteException,
JobParametersInvalidException {
JobParameters parameters = new JobParametersBuilder().addParameter("aa", new JobParameter("Hello World")).toJobParameters();
launcher.run(job, parameters);
}
}

Related

Error occur when i creating spring batch multiple JobBuild

I'm using kotlin, spring boot 3.0.1 and batch .
I create two of job/step configuration. but when i build the project, i've saw the below errors.
I'm asking a question because it's hard to change the previous batch example to the latest version. Has anyone solved this problem?
Strangely enough, if you take one job out on config, it can running it.
errors
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-01-03T13:47:34.101+09:00 ERROR 68470 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncherApplicationRunner': Invocation of init method failed
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:195) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:420) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1743) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.1.jar:3.0.1]
at com.linetest.batch.SpringBatchApplicationKt.main(SpringBatchApplication.kt:15) ~[main/:na]
Caused by: java.lang.IllegalArgumentException: Job name must be specified in case of multiple jobs
at org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.validate(JobLauncherApplicationRunner.java:116) ~[spring-boot-autoconfigure-3.0.1.jar:3.0.1]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:424) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:368) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:192) ~[spring-beans-6.0.3.jar:6.0.3]
... 17 common frames omitted
config/SingleStepJobConfig.kt
import com.linetest.batch.tasklet.SimpleTasklet
import mu.KotlinLogging
import org.springframework.batch.core.Job
import org.springframework.batch.core.Step
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.job.builder.JobBuilder
import org.springframework.batch.core.repository.JobRepository
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.builder.StepBuilder
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.transaction.PlatformTransactionManager
private val log = KotlinLogging.logger {}
#Configuration
class SingleStepJobConfig(
private val transactionManager: PlatformTransactionManager,
private val jobRepository: JobRepository,
) {
#Bean
fun singleStepJob(): Job {
return JobBuilder("singleStepJob", jobRepository)
.start(singleStep())
.build()
}
#Bean
fun singleStep(): Step {
return StepBuilder("singleStep", jobRepository)
.tasklet(myTaskletAsBean(), transactionManager)
.build()
}
#Bean
fun singleStep2(): Step {
return StepBuilder("singleStep2", jobRepository)
.tasklet({
_: StepContribution,
_: ChunkContext ->
log.info { "single step2 tasklet 2 test" }
RepeatStatus.FINISHED
}, transactionManager)
.build()
}
#Bean
fun myTaskletAsBean(): SimpleTasklet {
val simpleTasklet = SimpleTasklet()
simpleTasklet.setValue("Single Step Job Properties Setup!!!<<--")
return simpleTasklet
}
}
config/MultipleStepJobConfig.kt
import com.linetest.batch.tasklet.SimpleTasklet
import mu.KotlinLogging
import org.apache.logging.log4j.util.Strings
import org.springframework.batch.core.Job
import org.springframework.batch.core.Step
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing
import org.springframework.batch.core.job.builder.JobBuilder
import org.springframework.batch.core.repository.JobRepository
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.builder.StepBuilder
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.batch.BatchProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.transaction.PlatformTransactionManager
private val log = KotlinLogging.logger {}
#Configuration
class MultipleStepJobConfig(
private val transactionManager: PlatformTransactionManager,
private val jobRepository: JobRepository,
) {
#Bean
fun multipleStepJob(): Job {
return JobBuilder("multipleStepJob", jobRepository)
.start(startStep())
.next(processStep())
.next(writeStep())
.build()
}
#Bean
fun startStep(): Step {
return StepBuilder("startStep", jobRepository)
.tasklet({
_: StepContribution,
_: ChunkContext ->
log.info { "multiple Step Start" }
RepeatStatus.FINISHED
}, transactionManager)
.build()
}
#Bean
fun processStep(): Step {
return StepBuilder("processStep", jobRepository)
.tasklet({_: StepContribution,
_: ChunkContext ->
log.info { "Execute processStep >>>>" }
RepeatStatus.FINISHED
}, transactionManager)
.build()
}
#Bean
fun writeStep(): Step {
return StepBuilder("writeStep", jobRepository)
.tasklet({_: StepContribution,
_: ChunkContext ->
log.info { "Execute writeStep >>>>" }
RepeatStatus.FINISHED
}, transactionManager)
.build()
}
}
tasklet/SimpleTasklet.kt
import mu.KotlinLogging
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.configuration.annotation.StepScope
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.tasklet.Tasklet
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.beans.factory.InitializingBean
import org.springframework.stereotype.Component
private val log = KotlinLogging.logger { }
#Component
#StepScope
class SimpleTasklet : Tasklet, InitializingBean {
private var resource: String? = null
#Throws(Exception::class)
override fun execute(
contribution: StepContribution,
chunkContext: ChunkContext
): RepeatStatus? {
log.info { "Execute SimpleTasklet >>>>" }
return RepeatStatus.FINISHED
}
fun setValue(text:String){
this.resource = text
log.info { "$resource"}
}
#Throws(Exception::class)
override fun afterPropertiesSet() {
log.info { "AfterPropertiesSet" }
}
}
SpringBatchApplication.kt
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
#SpringBootApplication
class SpringBatchApplication
fun main(args: Array<String>) {
runApplication<SpringBatchApplication>(*args)
}
Strangely enough, if you take one job out on config, it can running it.
Existing Example can running.
ref. https://www.devkuma.com/docs/spring-batch/start/
the result
spring boot 2.5.5
2023-01-04 00:05:48.365 INFO 7829 --- [ main] com.linetest.batch.BatchApplicationKt : Starting BatchApplicationKt using Java 17.0.5 on mC02YR40ALVDL with PID 7829 (/Users/ParkJiho/Documents/workspace/kotlin/spring-batch-test-0102/build/classes/kotlin/main started by ParkJiho in /Users/ParkJiho/Documents/workspace/kotlin/spring-batch-test-0102)
2023-01-04 00:05:48.366 INFO 7829 --- [ main] com.linetest.batch.BatchApplicationKt : No active profile set, falling back to default profiles: default
2023-01-04 00:05:49.267 INFO 7829 --- [ main] c.linetest.batch.tasklet.SimpleTasklet : TESTTESTTEST has been set!!!!!!!!!!1
2023-01-04 00:05:49.267 INFO 7829 --- [ main] c.linetest.batch.tasklet.SimpleTasklet : AfterPropertiesSet
2023-01-04 00:05:49.282 INFO 7829 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-01-04 00:05:49.433 INFO 7829 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-01-04 00:05:49.538 INFO 7829 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: H2
2023-01-04 00:05:49.665 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2023-01-04 00:05:49.722 INFO 7829 --- [ main] com.linetest.batch.BatchApplicationKt : Started BatchApplicationKt in 1.659 seconds (JVM running for 2.351)
2023-01-04 00:05:49.723 INFO 7829 --- [ main] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
2023-01-04 00:05:49.766 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=flowStepJob]] launched with the following parameters: [{}]
2023-01-04 00:05:49.799 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [flowStartStep]
2023-01-04 00:05:49.806 INFO 7829 --- [ main] c.l.batch.config.FlowStepJobConfig : Flow Start Step!!<------
2023-01-04 00:05:49.811 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [flowStartStep] executed in 12ms
2023-01-04 00:05:49.816 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [flowProcessStep]
2023-01-04 00:05:49.818 INFO 7829 --- [ main] c.l.batch.config.FlowStepJobConfig : flowProcessStep
2023-01-04 00:05:49.819 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [flowProcessStep] executed in 3ms
2023-01-04 00:05:49.823 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [flowWriteStep]
2023-01-04 00:05:49.825 INFO 7829 --- [ main] c.l.batch.config.FlowStepJobConfig : flowWriteStep
2023-01-04 00:05:49.827 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [flowWriteStep] executed in 3ms
2023-01-04 00:05:49.830 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=flowStepJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 40ms
2023-01-04 00:05:49.833 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=multipleStepJob]] launched with the following parameters: [{}]
2023-01-04 00:05:49.837 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [startStep]
2023-01-04 00:05:49.839 INFO 7829 --- [ main] c.l.batch.config.MultipleStepJobConfig : Start Step<--------
2023-01-04 00:05:49.841 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [startStep] executed in 4ms
2023-01-04 00:05:49.844 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [nextStep]
2023-01-04 00:05:49.846 INFO 7829 --- [ main] c.l.batch.config.MultipleStepJobConfig : Next Step<--------
2023-01-04 00:05:49.847 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [nextStep] executed in 3ms
2023-01-04 00:05:49.850 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [lastStep]
2023-01-04 00:05:49.852 INFO 7829 --- [ main] c.l.batch.config.MultipleStepJobConfig : Last Step<--------
2023-01-04 00:05:49.853 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [lastStep] executed in 3ms
2023-01-04 00:05:49.855 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=multipleStepJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 21ms
2023-01-04 00:05:49.858 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=singleStepJob]] launched with the following parameters: [{}]
2023-01-04 00:05:49.861 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [simpleStep]
2023-01-04 00:05:49.862 INFO 7829 --- [ main] c.linetest.batch.tasklet.SimpleTasklet : Execute SimpleTasklet >>>>
2023-01-04 00:05:49.864 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [simpleStep] executed in 3ms
2023-01-04 00:05:49.865 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=singleStepJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 7ms
2023-01-04 00:05:49.869 INFO 7829 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2023-01-04 00:05:49.871 INFO 7829 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
The issue very clear from logs.
Caused by: java.lang.IllegalArgumentException: Job name must be specified in case of multiple jobs
at org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.validate(JobLauncherApplicationRunner.java:116) ~[spring-boot-autoconfigure-3.0.1.jar:3.0.1]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:424) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:368) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:192) ~[spring-beans-6.0.3.jar:6.0.3]
... 17 common frames omitted
If only one job is present in Spring Context then Spring run that job by default on startup but If multiple jobs are present in Spring Context then we need to tell Spring which job to run on startup.
So you can specify this property in application.properties file and try again.
spring.batch.job.name=singleStepJob
or
spring.batch.job.name=multipleStepJob
or you can disable running job on startup by this property and run the job programmatically using JobLauncher.
spring.batch.job.enabled=false
How to run job programmatically?
public class JobLauncherService {
private final JobLauncher jobLauncher;
private final Job job;
#Autowired
public JobLauncherService(JobLauncher jobLauncher, #Qualifier("multipleStepJob") Job job) {
this.jobLauncher = jobLauncher;
this.job = job;
}
public void runJob() {
try {
final JobExecution jobExecution = jobLauncher.run(job, new JobParameters());
System.out.println("Job Status : " + jobExecution.getStatus());
System.out.println("Job completed");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Job failed");
}
}
}

Postman - 401 unauthorized status | Spring Boot

I prepared very simple REST APi.
I am trying to do requests with postman but i get 401 Unauthorized. No matter what kind request it is. I have Windows 11 system, Java 11, Postman Version 9.8.2
Postman:
application.properties file:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/students
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
Spring Application:
#SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
public class StudentsmanagerApplication {
public static void main(String[] args) {
SpringApplication.run(StudentsmanagerApplication.class, args);
}
Controller class:
#RestController
#RequestMapping("/student")
public class StudentController {
private StudentService studentService;
#GetMapping
public ResponseEntity<List<Student>> getAllStudents() {
List<Student> students = studentService.findAllStudent();
return new ResponseEntity<>(students, HttpStatus.OK);
}
#GetMapping("find/{id}")
public ResponseEntity<Student> getAllStudentsById(#PathVariable Long id) {
Student student = studentService.findStudentById(id);
return new ResponseEntity<>(student, HttpStatus.OK);
}
#PostMapping
public ResponseEntity<Student> addEmployee(#RequestBody Student student) {
Student newStudent = studentService.addStudent(student);
return new ResponseEntity<>(newStudent, HttpStatus.CREATED);
}
#PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(#PathVariable Long id, #RequestBody Student
student) {
Student updatedStudent = studentService.updateStudent(id, student);
return new ResponseEntity<>(updatedStudent, HttpStatus.UPGRADE_REQUIRED);
}
#DeleteMapping("/{id}")
public ResponseEntity<?> deleteStudent(#PathVariable Long id) {
studentService.deleteStudent(id);
return new ResponseEntity<>(HttpStatus.OK);
}
Service class:
#Service
public class StudentService {
private StudentRepository studentRepository;
public Student addStudent(Student student) {
student.setStudentCode(UUID.randomUUID().toString());
return studentRepository.save(student);
}
public List<Student> findAllStudent() {
return studentRepository.findAll();
}
public Student updateStudent(Long id, Student student) {
Student studentById = studentRepository
.findById(id).orElseThrow(() -> new StudentNotFoundException("Student by id
" + " doesn't Exist"));
studentById.setName(student.getName());
studentById.setLastName(student.getLastName());
studentById.setEmail(student.getEmail());
studentById.setPhone(student.getPhone());
return studentRepository.save(studentById);
}
public Student findStudentById(Long id) {
return studentRepository
.findById(id).orElseThrow(() -> new StudentNotFoundException("Student
doesn't exist "));
}
public void deleteStudent(Long id) {
studentRepository.deleteById(id);
}
Spring logs:
2022-01-08 10:53:19.661 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : Starting StudentsmanagerApplication using Java 11.0.13 on LAPTOP-9F9MO24J with PID 20120 (C:\Users\mkord\IdeaProjects\studentsmanager\target\classes started by mkord in C:\Users\mkord\IdeaProjects\studentsmanager)
2022-01-08 10:53:19.661 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : No active profile set, falling back to default profiles: default
2022-01-08 10:53:20.539 INFO 20120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-01-08 10:53:20.596 INFO 20120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 50 ms. Found 1 JPA repository interfaces.
2022-01-08 10:53:21.262 INFO 20120 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-01-08 10:53:21.278 INFO 20120 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-08 10:53:21.278 INFO 20120 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-01-08 10:53:21.422 INFO 20120 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-01-08 10:53:21.422 INFO 20120 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1684 ms
2022-01-08 10:53:21.662 INFO 20120 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-01-08 10:53:21.703 INFO 20120 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.3.Final
2022-01-08 10:53:21.856 INFO 20120 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-01-08 10:53:21.976 INFO 20120 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-08 10:53:22.336 INFO 20120 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-01-08 10:53:22.352 INFO 20120 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2022-01-08 10:53:22.968 INFO 20120 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-01-08 10:53:22.984 INFO 20120 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-01-08 10:53:23.032 WARN 20120 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-01-08 10:53:23.824 INFO 20120 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#36931450, org.springframework.security.web.context.SecurityContextPersistenceFilter#451a4187, org.springframework.security.web.header.HeaderWriterFilter#6db04a6, org.springframework.security.web.csrf.CsrfFilter#630c3af3, org.springframework.security.web.authentication.logout.LogoutFilter#4866e0a7, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#66d44581, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#4ac0d49, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#74919649, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#2ea4e762, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#5c215642, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#1317ac2c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#7d07e04e, org.springframework.security.web.session.SessionManagementFilter#426913c4, org.springframework.security.web.access.ExceptionTranslationFilter#38197e82, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#5a07ae2f]
2022-01-08 10:53:23.914 INFO 20120 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-01-08 10:53:23.930 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : Started StudentsmanagerApplication in 4.851 seconds (JVM running for 6.309)
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
2022-01-08 10:59:13.941 WARN 20120 --- [nio-8080-exec-2] o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [184] milliseconds.
Thank You in advance for any suggestion

CamelContextStartedEvent called twice

The CamelContextStartedEvent is called twice for the same camel context (camel-1). The issue might be the way I register the EventNotifier. You can reproduce the issue with Spring Initializr with Spring Boot 1.5.14, Spring Boot Camel Starter 2.21.1 and Spring Boot Web Starter.
See the logs:
2018-07-06 11:04:41.104 INFO 19092 --- [ main] o.a.camel.spring.SpringCamelContext : Apache Camel 2.21.1 (CamelContext: camel-1) is starting
2018-07-06 11:04:41.106 INFO 19092 --- [ main] o.a.c.m.ManagedManagementStrategy : JMX is enabled
2018-07-06 11:04:41.191 INFO 19092 --- [ main] o.a.camel.spring.SpringCamelContext : StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
2018-07-06 11:04:41.193 INFO 19092 --- [ main] o.a.camel.spring.boot.RoutesCollector : Starting CamelMainRunController to ensure the main thread keeps running
2018-07-06 11:04:41.193 INFO 19092 --- [ main] o.a.camel.spring.SpringCamelContext : Total 0 routes, of which 0 are started
2018-07-06 11:04:41.194 INFO 19092 --- [ main] o.a.camel.spring.SpringCamelContext : Apache Camel 2.21.1 (CamelContext: camel-1) started in 0.090 seconds
2018-07-06 11:04:41.195 INFO 19092 --- [ main] c.e.bug.service.StartupEventNotifier : CamelContextStartedEvent for SpringCamelContext(camel-1) with spring id application:11223
2018-07-06 11:04:41.195 INFO 19092 --- [ main] c.e.bug.service.StartupEventNotifier : CamelContextStartedEvent for SpringCamelContext(camel-1) with spring id application:11223
2018-07-06 11:04:41.216 INFO 19092 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 11223 (http)
2018-07-06 11:04:41.221 INFO 19092 --- [ main] com.example.bug.BugApplication : Started BugApplication in 4.684 seconds (JVM running for 6.773)
The service that initializes the EventNotifier:
#Service
public class SchedulerService {
private final CamelContext camelContext;
private final StartupEventNotifier startupEventNotifier;
public SchedulerService(CamelContext camelContext, StartupEventNotifier startupEventNotifier) {
this.camelContext = camelContext;
this.startupEventNotifier = startupEventNotifier;
}
#PostConstruct
public void init() {
camelContext.getManagementStrategy().addEventNotifier(startupEventNotifier);
}
}
The EventNotifier:
#Component
public class StartupEventNotifier extends EventNotifierSupport {
private static final Logger logger = LoggerFactory.getLogger(StartupEventNotifier.class);
#Override
public void notify(EventObject event) throws Exception {
if (event instanceof CamelContextStartedEvent) {
logger.info("CamelContextStartedEvent for {}", event.getSource());
}
}
#Override
public boolean isEnabled(EventObject event) {
if (event instanceof CamelContextStartedEvent) {
return true;
}
return false;
}
}
application.yml:
camel:
springboot:
main-run-controller: true
server:
port: 11223
It is called twice, because it is registered twice. Once by you and once by Apache Camel. EventNotifier is registered automatically, if is found in Registry. Since your StartupEventNotifier is annotated as Component, it is part of Registry and Apache Camel registered it during CamelContext startup (You can see it in CamelAutoConfiguration line 424).
You have four options:
Remove your custom registration from SchedulerService.
Remove #Component annotation from StartupEventNotifier and register it with with camelContext.getManagementStrategy().addEventNotifier(new StartupEventNotifier())
Add duplicity check to your SchedulerService. Something like:
if (!context.getManagementStrategy().getEventNotifiers().contains(startupEventNotifier)){
context.getManagementStrategy().addEventNotifier(startupEventNotifier);
}
Register EventNotifier in #PostConstruct of RouteBuilder. It will be registered before automatic discovery is started and then it will be skipped in CamelAutoConfiguration (See line 422)

Why Spring Boot Application logs that it started twice after adding spring-cloud-bus dependency

This is simple code in my Spring boot application:
package com.maxxton.SpringBootHelloWorld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
}
And a ApplicationListener class to listen to ApplicationEvent:
package com.maxxton.SpringBootHelloWorld;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
#Component
public class Test implements ApplicationListener {
#Override
public void onApplicationEvent(ApplicationEvent event) {
if (event.getClass().getSimpleName().equals("ApplicationReadyEvent")) {
System.out.println("-------------------------------------");
System.out.println(event.getClass().getSimpleName());
System.out.println("-------------------------------------");
}
}
}
build.gradle contains these dependencies:
dependencies {
compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter')
compile("org.springframework.cloud:spring-cloud-starter")
compile("org.springframework.cloud:spring-cloud-starter-security")
compile("org.springframework.cloud:spring-cloud-starter-eureka")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Now, when I run this spring boot application, I see this log printed twice:
[main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in ... seconds (JVM running for ...)
Usually, this log get printed only once, but it get printed twice if I add these dependencies:
compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")
This is complete log:
2017-11-17 15:44:07.372 INFO 5976 --- [ main] o.s.c.support.GenericApplicationContext : Refreshing org.springframework.context.support.GenericApplicationContext#31c7c281: startup date [Fri Nov 17 15:44:07 IST 2017]; root of context hierarchy
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:07.403 INFO 5976 --- [ main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in 1.19 seconds (JVM running for 10.231)
2017-11-17 15:44:09.483 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:09.492 INFO 5976 --- [ main] o.s.integration.channel.DirectChannel : Channel 'a-bootiful-client.springCloudBusOutput' has 1 subscriber(s).
2017-11-17 15:44:09.493 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'a-bootiful-client.errorChannel' has 1 subscriber(s).
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started _org.springframework.integration.errorLogger
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147482647
2017-11-17 15:44:09.539 INFO 5976 --- [ main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, bound to: springCloudBus
2017-11-17 15:44:11.562 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:13.587 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare queue: Queue [name=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, durable=false, autoDelete=true, exclusive=true, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:15.611 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare binding: Binding [destination=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, exchange=springCloudBus, routingKey=#], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.a.i.AmqpInboundChannelAdapter : started inbound.springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {message-handler:inbound.springCloudBus.default} as a subscriber to the 'bridge.springCloudBus' channel
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started inbound.springCloudBus.default
2017-11-17 15:44:17.663 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2017-11-17 15:44:17.714 INFO 5976 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:17.717 INFO 5976 --- [ main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in 20.131 seconds (JVM running for 20.545)
As you can see, ApplicationReadyEvent is happening twice.
Why is this happening?
Is there any way to avoid this?
spring-cloud-bus uses spring-cloud-stream which puts the binder in a separate boot child application context.
You should make your event listener aware of the application context it is running in. You can also use generics to select the event type you are interested in...
#Component
public class Test implements ApplicationListener<ApplicationReadyEvent>,
ApplicationContextAware {
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
#Override
public void onApplicationEvent(ApplicationReadyEvent event) {
if (event.getApplicationContext().equals(this.applicationContext)) {
System.out.println("-------------------------------------");
System.out.println(event.getClass().getSimpleName());
System.out.println("-------------------------------------");
}
}
}
Are u using multiple binders rabbitmq configuration in your application.yml/.xml ?
If it's a yes, then u can try to exclude RabbitAutoConfiguration.
#EnableDiscoveryClient
#EnableAutoConfiguration(exclude = {RabbitAutoConfiguration.class})
#SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
}

Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered

I know this has been asked many time but I could not
find answer for I problem. I am Trying to schedule my spring batch for every 20 second but its getting fail.
QuartzConfiguration.java
#Configuration
public class QuartzConfiguration {
#Autowired
private JobLauncher jobLauncher;
#Autowired
private JobLocator jobLocator;
#Bean
public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry) {
JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();
jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);
return jobRegistryBeanPostProcessor;
}
#Bean
public JobDetailFactoryBean jobDetailFactoryBean() {
JobDetailFactoryBean jobfactory = new JobDetailFactoryBean();
jobfactory.setJobClass(QuartzJobLauncher.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jobName", "Test_Job");
map.put("jobLauncher", jobLauncher);
map.put("jobLocator", jobLocator);
jobfactory.setJobDataAsMap(map);
jobfactory.setGroup("group");
jobfactory.setName("job");
return jobfactory;
}
// Job is scheduled after every 20 sec
#Bean
public CronTriggerFactoryBean cronTriggerFactoryBean() {
CronTriggerFactoryBean ctFactory = new CronTriggerFactoryBean();
ctFactory.setJobDetail(jobDetailFactoryBean().getObject());
ctFactory.setStartDelay(3000);
ctFactory.setName("cron_trigger");
ctFactory.setGroup("cron_group");
ctFactory.setCronExpression("0/20 * * * * ?");
return ctFactory;
}
#Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
scheduler.setTriggers(cronTriggerFactoryBean().getObject());
return scheduler;
}
}
QuartzJobLauncher.java
public class QuartzJobLauncher extends QuartzJobBean {
private static final Logger log = LoggerFactory.getLogger(QuartzJobLauncher.class);
private String jobName;
private JobLauncher jobLauncher;
private JobLocator jobLocator;
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public JobLauncher getJobLauncher() {
return jobLauncher;
}
public void setJobLauncher(JobLauncher jobLauncher) {
this.jobLauncher = jobLauncher;
}
public JobLocator getJobLocator() {
return jobLocator;
}
public void setJobLocator(JobLocator jobLocator) {
this.jobLocator = jobLocator;
}
#Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
Job job = jobLocator.getJob(jobName);
JobExecution jobExecution = jobLauncher.run(job, new JobParameters());
log.info("{}_{} was completed successfully", job.getName(), jobExecution.getId());
} catch (Exception e) {
log.error("Encountered job execution exception!");
}
}
}
BatchConfig.java
#Configuration
public class BatchConfig {
#Autowired
JobBuilderFactory jobBuilderFactory;
#Autowired
StepBuilderFactory stepBuilderFactory;
#Bean
public Tasklet task1()
{
return new Tasklet(){
#Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
// TODO Auto-generated method stub
System.out.println("hello world");
return RepeatStatus.FINISHED;
}
};
}
#Bean
public Step step1(){
return stepBuilderFactory.get("step1")
.tasklet(task1())
.build();
}
#Bean
public Job job1()
{
return jobBuilderFactory.get("job1")
.start(step1())
.build();
}
}
BatchApplication.java
#SpringBootApplication
#EnableBatchProcessing
#Import(QuartzConfiguration.class)
public class BatchApplication {
public static void main(String[] args) {
SpringApplication.run(BatchApplication.class, args);
}
}
error log
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.4.RELEASE)
2017-07-11 14:35:59.370 INFO 8868 --- [ main] com.schwab.cat.BatchApplication : Starting BatchApplication on KVMOF0487DVLBDC with PID 8868 (started by pankaj.k.singh in C:\Users\pankaj.k.singh\Desktop\batch\sample hello world)
2017-07-11 14:35:59.377 INFO 8868 --- [ main] com.schwab.cat.BatchApplication : No active profile set, falling back to default profiles: default
2017-07-11 14:35:59.511 INFO 8868 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#221af3c0: startup date [Tue Jul 11 14:35:59 IST 2017]; root of context hierarchy
2017-07-11 14:36:00.992 WARN 8868 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2017-07-11 14:36:01.013 WARN 8868 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2017-07-11 14:36:01.230 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.253 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$1bb5301] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.435 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.632 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'dataSource' of type [org.apache.tomcat.jdbc.pool.DataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.641 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$$EnhancerBySpringCGLIB$$e3aef661] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.672 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'dataSourceInitializer' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.679 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration' of type [org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$$EnhancerBySpringCGLIB$$17e2d67] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.718 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'jobLauncher' of type [com.sun.proxy.$Proxy41] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.732 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'jobRegistry' of type [com.sun.proxy.$Proxy43] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.733 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'com.quantvalley.batch.quartz.QuartzConfiguration' of type [com.quantvalley.batch.quartz.QuartzConfiguration$$EnhancerBySpringCGLIB$$88291ebb] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:03.256 INFO 8868 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2017-07-11 14:36:03.606 INFO 8868 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2017-07-11 14:36:03.912 INFO 8868 --- [ main] org.quartz.impl.StdSchedulerFactory : Using default implementation for ThreadExecutor
2017-07-11 14:36:03.980 INFO 8868 --- [ main] org.quartz.core.SchedulerSignalerImpl : Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2017-07-11 14:36:03.984 INFO 8868 --- [ main] org.quartz.core.QuartzScheduler : Quartz Scheduler v.2.2.3 created.
2017-07-11 14:36:03.987 INFO 8868 --- [ main] org.quartz.simpl.RAMJobStore : RAMJobStore initialized.
2017-07-11 14:36:03.991 INFO 8868 --- [ main] org.quartz.core.QuartzScheduler : Scheduler meta-data: Quartz Scheduler (v2.2.3) 'schedulerFactoryBean' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
2017-07-11 14:36:03.993 INFO 8868 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler 'schedulerFactoryBean' initialized from an externally provided properties instance.
2017-07-11 14:36:03.993 INFO 8868 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler version: 2.2.3
2017-07-11 14:36:03.998 INFO 8868 --- [ main] org.quartz.core.QuartzScheduler : JobFactory set to: org.springframework.scheduling.quartz.AdaptableJobFactory#20312893
2017-07-11 14:36:04.335 INFO 8868 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2017-07-11 14:36:04.366 INFO 8868 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 25 ms.
2017-07-11 14:36:04.733 INFO 8868 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-07-11 14:36:04.748 INFO 8868 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2017-07-11 14:36:04.749 INFO 8868 --- [ main] o.s.s.quartz.SchedulerFactoryBean : Starting Quartz Scheduler now
2017-07-11 14:36:04.750 INFO 8868 --- [ main] org.quartz.core.QuartzScheduler : Scheduler schedulerFactoryBean_$_NON_CLUSTERED started.
2017-07-11 14:36:04.773 INFO 8868 --- [ main] com.schwab.cat.BatchApplication : Started BatchApplication in 6.481 seconds (JVM running for 11.417)
2017-07-11 14:36:20.039 ERROR 8868 --- [ryBean_Worker-1] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:36:40.006 ERROR 8868 --- [ryBean_Worker-2] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:37:00.001 ERROR 8868 --- [ryBean_Worker-3] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:37:20.002 ERROR 8868 --- [ryBean_Worker-4] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:37:40.002 ERROR 8868 --- [ryBean_Worker-5] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:38:00.002 ERROR 8868 --- [ryBean_Worker-6] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
Please someone look into it and let me know the problem.
You swallowed the exception in your try/catch and instead, you logged only the fact that exception occurrent, but not what kind of exception it was. If you change logging statement to this:
log.error("Encountered job execution exception!", e);
You'll see that the error says:
org.springframework.batch.core.launch.NoSuchJobException: No job configuration with the name [Test_Job] was registered
You have declared a job with name job1, not Test_Job so that's why you're getting the exception. You have to change job data map to:
map.put("jobName", "job1");
This will remove the exception, but your job will still run once as Spring Batch requires unique job parameters to restart it, see this answer for explanation.
So because of that, you have to modify your job execution to something like this (the simplest) to be able to run it continually:
#Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
Job job = jobLocator.getJob(jobName);
Map<String, JobParameter> parametersMap = new HashMap<>();
parametersMap.put("timestamp", new JobParameter(System.currentTimeMillis()));
JobParameters jobParameters = new JobParameters(parametersMap);
JobExecution jobExecution = jobLauncher.run(job, jobParameters);
log.info("{}_{} was completed successfully", job.getName(), jobExecution.getId());
} catch (Exception e) {
log.error("Encountered job execution exception!", e);
}
}

Resources