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

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);
}
}

Related

Spring Batch 5.0 with Spring Boot -- Tasklet job not starting automatically

I have a very simple Spring Boot project with Spring Batch 5.0 and a CommmandLineRunner. There is one Job, one step, and one tasklet that simply prints "Running".
I followed directions and would expect the job to start and complete.
No errors; the Batch database table are being created; the Job and Step beans are being created.
It just doesn't run.
I would be grateful for any insights or assistance!
NOTE: If I launch the job explicitly from the CommandLineRunner using an autowired JobLauncher, it works fine. It just doesn't launch the job automatically (as promised).
NOTE 2: Removing #EnableBatchProcessing makes no difference.
Code follows
application.properties:
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost/postgres
spring.batch.jdbc.initialize-schema=always
spring.batch.job.enabled=true
Application.java:
#SpringBootApplication
#EnableBatchProcessing
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Starting...");
Thread.sleep(2000);
}
}
Job configuration:
#Configuration
public class AbacusJobConfiguration {
Logger logger = LoggerFactory.getLogger(AbacusJobConfiguration.class);
#Bean
public Step step(JobRepository jobRepository, PlatformTransactionManager transactionManager, Tasklet tasklet1) {
logger.info("Building step");
return new StepBuilder("myTasklet", jobRepository)
.tasklet(tasklet1, transactionManager).allowStartIfComplete(true)
.build();
}
#Bean
public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager, Step step1) {
return new JobBuilder("myJob", jobRepository)
.incrementer(new RunIdIncrementer())
.start(step1)
.build();
}
#Bean
public MyTasklet myTasklet() {
logger.info("Building tasklet");
var tasklet = new MyTasklet();
return tasklet;
}
}
Tasklet:
public class MyTasklet implements Tasklet {
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("Running MyTasklet");
return RepeatStatus.FINISHED;
}
}
Runtime log:
2023-01-30T10:54:07.407-05:00 INFO 72774 --- [ main] c.optionmetrics.abacuscli.Application : Starting Application using Java 17.0.6 with PID 72774 (/Users/dhait/IdeaProjects/abacus-cli/target/classes started by dhait in /Users/dhait/IdeaProjects/abacus-cli)
2023-01-30T10:54:07.410-05:00 INFO 72774 --- [ main] c.optionmetrics.abacuscli.Application : No active profile set, falling back to 1 default profile: "default"
2023-01-30T10:54:07.626-05:00 INFO 72774 --- [ main] o.s.b.c.c.annotation.BatchRegistrar : Finished Spring Batch infrastructure beans configuration in 2 ms.
2023-01-30T10:54:07.836-05:00 INFO 72774 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-01-30T10:54:07.918-05:00 INFO 72774 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection#6ae7deac
2023-01-30T10:54:07.919-05:00 INFO 72774 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-01-30T10:54:07.928-05:00 INFO 72774 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: POSTGRES
2023-01-30T10:54:07.940-05:00 INFO 72774 --- [ main] c.o.abacuscli.AbacusJobConfiguration : Building tasklet
2023-01-30T10:54:07.942-05:00 INFO 72774 --- [ main] c.o.abacuscli.AbacusJobConfiguration : Building step
2023-01-30T10:54:07.954-05:00 INFO 72774 --- [ main] .c.a.BatchObservabilityBeanPostProcessor : No Micrometer observation registry found, defaulting to ObservationRegistry.NOOP
2023-01-30T10:54:07.959-05:00 INFO 72774 --- [ main] .c.a.BatchObservabilityBeanPostProcessor : No Micrometer observation registry found, defaulting to ObservationRegistry.NOOP
2023-01-30T10:54:07.963-05:00 INFO 72774 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2023-01-30T10:54:08.040-05:00 INFO 72774 --- [ main] c.optionmetrics.abacuscli.Application : Started Application in 0.882 seconds (process running for 1.246)
Starting...
2023-01-30T10:54:10.050-05:00 INFO 72774 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2023-01-30T10:54:10.054-05:00 INFO 72774 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
With Spring Boot 3, there is no need for #EnableBatchProcessing. If you add it, the auto-configuration of Spring Batch (including the automatic launching of jobs at startup) will back off.
This is mentioned in the migration guide of Spring Boot 3.
EDIT: Not able to reproduce the issue. Things are working as expected with Spring Batch 5 and Spring Boot 3.
$>curl https://start.spring.io/starter.zip -d dependencies=h2,batch -d type=maven-project -o my-batch-job.zip
$>unzip my-batch-job.zip
$> # Paste AbacusJobConfiguration and MyTasklet code in the demo package + add imports
$>./mvnw package
$>./mvnw spring-boot:run
This prints:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.2)
2023-01-31T07:48:24.206+01:00 INFO 91983 --- [ main] com.example.demo.DemoApplicationTests : Starting DemoApplicationTests using Java 17.0.4 with PID 91983 (started by mbenhassine in /Users/mbenhassine/Downloads/so75287102)
2023-01-31T07:48:24.207+01:00 INFO 91983 --- [ main] com.example.demo.DemoApplicationTests : No active profile set, falling back to 1 default profile: "default"
2023-01-31T07:48:24.625+01:00 INFO 91983 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-01-31T07:48:24.779+01:00 INFO 91983 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:0b237f7c-fec8-446f-b2ac-086801ddb7fd user=SA
2023-01-31T07:48:24.780+01:00 INFO 91983 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-01-31T07:48:24.858+01:00 INFO 91983 --- [ main] c.example.demo.AbacusJobConfiguration : Building tasklet
2023-01-31T07:48:24.860+01:00 INFO 91983 --- [ main] c.example.demo.AbacusJobConfiguration : Building step
2023-01-31T07:48:24.957+01:00 INFO 91983 --- [ main] com.example.demo.DemoApplicationTests : Started DemoApplicationTests in 0.91 seconds (process running for 1.585)
2023-01-31T07:48:24.958+01:00 INFO 91983 --- [ main] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
2023-01-31T07:48:24.990+01:00 INFO 91983 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=myJob]] launched with the following parameters: [{'run.id':'{value=1, type=class java.lang.Long, identifying=true}'}]
2023-01-31T07:48:25.009+01:00 INFO 91983 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [myTasklet]
Running MyTasklet
2023-01-31T07:48:25.017+01:00 INFO 91983 --- [ main] o.s.batch.core.step.AbstractStep : Step: [myTasklet] executed in 8ms
2023-01-31T07:48:25.025+01:00 INFO 91983 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=myJob]] completed with the following parameters: [{'run.id':'{value=1, type=class java.lang.Long, identifying=true}'}] and the following status: [COMPLETED] in 23ms
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.556 s - in com.example.demo.DemoApplicationTests
2023-01-31T07:48:25.312+01:00 INFO 91983 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2023-01-31T07:48:25.315+01:00 INFO 91983 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.

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

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);
}
}

A component required a bean named 'entityManagerFactory' that could not be found

I am doing a project in SpringBoot using Postgres and restful approach. My application is failing to start.I am new to this.Please help me with this problem.Below is my code:
Error
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.2-SNAPSHOT)
2020-12-30 21:42:08.397 INFO 7284 --- [ restartedMain] com.cg.pps.SpringRestApplication : Starting SpringRestApplication using Java 15.0.1 on DESKTOP-7ODO40V with PID 7284 (D:\E drive\studymaterial\Sprint2\PersonalityPredictionSystemMus\target\classes started by BST in D:\E drive\studymaterial\Sprint2\PersonalityPredictionSystemMus)
2020-12-30 21:42:08.410 INFO 7284 --- [ restartedMain] com.cg.pps.SpringRestApplication : No active profile set, falling back to default profiles: default
2020-12-30 21:42:08.677 INFO 7284 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-12-30 21:42:08.678 INFO 7284 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-12-30 21:42:10.722 INFO 7284 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-12-30 21:42:10.921 INFO 7284 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 165 ms. Found 1 JPA repository interfaces.
2020-12-30 21:42:12.831 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:12.848 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'relProviderPluginRegistry' of type [org.springframework.plugin.core.support.PluginRegistryFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:12.896 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'relProviderPluginRegistry' of type [org.springframework.plugin.core.OrderAwarePluginRegistry] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:12.907 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean '_relProvider' of type [org.springframework.hateoas.server.core.DelegatingLinkRelationProvider] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:12.933 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'messageResolver' of type [org.springframework.hateoas.mediatype.MessageSourceResolver] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:12.936 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.data.web.config.SpringDataJacksonConfiguration' of type [org.springframework.data.web.config.SpringDataJacksonConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:12.952 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'jacksonGeoModule' of type [org.springframework.data.geo.GeoModule] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.002 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration' of type [org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.011 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration' of type [org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.018 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration' of type [org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.097 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties' of type [org.springframework.boot.autoconfigure.jackson.JacksonProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.100 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'standardJacksonObjectMapperBuilderCustomizer' of type [org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration$StandardJackson2ObjectMapperBuilderCustomizer] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.106 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration' of type [org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.112 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'parameterNamesModule' of type [com.fasterxml.jackson.module.paramnames.ParameterNamesModule] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.114 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration' of type [org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.137 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'jsonComponentModule' of type [org.springframework.boot.jackson.JsonComponentModule] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.145 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'jacksonObjectMapperBuilder' of type [org.springframework.http.converter.json.Jackson2ObjectMapperBuilder] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.165 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'spring.data.rest-org.springframework.boot.autoconfigure.data.rest.RepositoryRestProperties' of type [org.springframework.boot.autoconfigure.data.rest.RepositoryRestProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.166 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'springBootRepositoryRestConfigurer' of type [org.springframework.boot.autoconfigure.data.rest.SpringBootRepositoryRestConfigurer] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.169 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'configurerDelegate' of type [org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerDelegate] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.185 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration' of type [org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.204 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'stringHttpMessageConverter' of type [org.springframework.http.converter.StringHttpMessageConverter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.207 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration' of type [org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.210 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration' of type [org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.224 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'jacksonObjectMapperBuilder' of type [org.springframework.http.converter.json.Jackson2ObjectMapperBuilder] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.279 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'jacksonObjectMapper' of type [com.fasterxml.jackson.databind.ObjectMapper] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.284 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'mappingJackson2HttpMessageConverter' of type [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:13.286 INFO 7284 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration' of type [org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-12-30 21:42:14.804 INFO 7284 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8082 (http)
2020-12-30 21:42:14.840 INFO 7284 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-12-30 21:42:14.841 INFO 7284 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2020-12-30 21:42:15.409 INFO 7284 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-12-30 21:42:15.410 INFO 7284 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 6731 ms
2020-12-30 21:42:16.076 WARN 7284 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cvRepo' defined in com.cg.pps.repository.CvRepo defined in #EnableJpaRepositories declared on SpringRestApplication: Cannot create inner bean '(inner bean)#2fe84e0e' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2fe84e0e': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2020-12-30 21:42:16.089 INFO 7284 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-12-30 21:42:16.173 INFO 7284 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-30 21:42:16.308 ERROR 7284 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
App.java
package com.cg.pps;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
#EnableJpaRepositories(basePackages = {"com.cg.pps.repository"})
#SpringBootApplication
public class SpringRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestApplication.class, args);
}
}
Controller
package com.cg.pps.controller;
import java.util.List;
import com.cg.pps.model.*;
import com.cg.pps.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController()
#RequestMapping("/candidatecv")
public class CandidateCvController {
#Autowired
private CandidateCvs candidatecvs;
#GetMapping("/getall")
public List<CandidateCv> getAllPeople() {
return candidatecvs.getAllCandiateCv();
}
#GetMapping("/get/{id}")
public CandidateCv getCandidateCvByEmail(#PathVariable String email) {
return candidatecvs.getCandidateCvByEmail(email);
}
#PostMapping("/create")
public String createCandidateCv(#PathVariable CandidateCv cv) {
if(cv != null) {
candidatecvs.createCandidateCv(cv);
return "Cv Added";
} else {
return "Request does not contain a body";
}
}
}
model
package com.cg.pps.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//import the job package
#Entity
#Table(name="cand_info")
public class CandidateCv implements Serializable {
#Id
#Column(name="CandidateName", length=20)
private String CandidateName;
#Column(name="Email",length=12 ,unique=true)
private String email;
#Column(name="Phoneno",length=10)
private int phoneno;
#Column(name="Qualification",length=10)
private String qualification;
#Column(name="Experience",length=2)
private int exp;
#Column(name="Skill",length=10)
private String skill;
public CandidateCv() {
// TODO Auto-generated constructor stub
}
public CandidateCv(String candidateName, String email, int phoneno, String qualification, int exp, String skill) {
super();
CandidateName = candidateName;
this.email = email;
this.phoneno = phoneno;
this.qualification = qualification;
this.exp = exp;
this.skill = skill;
}
public String getCandidateName() {
return CandidateName;
}
public void setCandidateName(String candidateName) {
CandidateName = candidateName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPhoneno() {
return phoneno;
}
public void setPhoneno(int phoneno) {
this.phoneno = phoneno;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
}
Repository
package com.cg.pps.repository;
import com.cg.pps.model.CandidateCv;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CvRepo extends CrudRepository<CandidateCv, Long> {
public boolean existByEmail(String email);
public CandidateCv findByEmail(String email);
}
ServiceInterface
package com.cg.pps.service;
import com.cg.pps.model.*;
import java.util.List;
import org.springframework.stereotype.Service;
public interface CandidateCvs {
List<CandidateCv> getAllCandiateCv();
CandidateCv getCandidateCvByEmail(String email);
String createCandidateCv(CandidateCv e);
}
**Service Implementation**
package com.cg.pps.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.cg.pps.repository.CvRepo;
import com.cg.pps.model.CandidateCv;
#Transactional
#Service
public class CandidateCvImpl implements CandidateCvs {
private CvRepo repository;
#Override
public List<CandidateCv> getAllCandiateCv() {
return (List<CandidateCv>)repository.findAll();
}
#Override
public String createCandidateCv(CandidateCv e) {
String id=e.getEmail();
if(repository.existByEmail(id))
{
return "Candidate Cv already exists";
}
else {
repository.save(e);
return "Employee data successfully saved";
}
}
#Override
public CandidateCv getCandidateCvByEmail(String email) {
CandidateCv cv= new CandidateCv();
String id=cv.getEmail();
if(repository.existByEmail(id)) {
return repository.findByEmail(email);
}
else
{
return null;
}
}
}
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Please review my above codes and let me know what I am doing wrong.

Spring Cloud Kubernetes - Spring boot fails to start when config reload is enabled

I have this demo project which prints a label that is read from the configurations.
This is my main class:
#SpringBootApplication
#EnableDiscoveryClient
#RestController
public class DemoApplication {
private MyConfig config;
private DiscoveryClient discoveryClient;
#Autowired
public DemoApplication(MyConfig config, DiscoveryClient discoveryClient) {
this.config = config;
this.discoveryClient = discoveryClient;
}
#RequestMapping("/")
public String info() {
return config.getMessage();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RequestMapping("/services")
public String services() {
StringBuilder b = new StringBuilder();
discoveryClient.getServices().forEach((s) -> b.append(s).append(" , "));
return b.toString();
}
}
And the MyConfig class is:
#Configuration
#ConfigurationProperties(prefix = "bean")
public class MyConfig {
private String message = "a message that can be changed live";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
The bootstrap.properties contain:
spring.application.name=demo
spring.cloud.kubernetes.config.name=demo
spring.cloud.kubernetes.config.enabled=true
spring.cloud.kubernetes.config.namespace=default
spring.cloud.kubernetes.reload.enabled=true
spring.cloud.kubernetes.reload.monitoring-config-maps=true
spring.cloud.kubernetes.reload.strategy=refresh
spring.cloud.kubernetes.reload.mode=event
management.endpoint.refresh.enabled=true
management.endpoints.web.exposure.include=*
And the dependencies in build.gradle:
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter-kubernetes:+")
compile("org.springframework.cloud:spring-cloud-starter-kubernetes-config:+")
testCompile('org.springframework.boot:spring-boot-starter-test')
runtime("org.springframework.boot:spring-boot-properties-migrator")
}
I'm creating the ConfigMap with kubectl create -f configmap-demo.yml being the content:
apiVersion: v1
kind: ConfigMap
metadata:
name: demo
data:
bean.message: This is an info from k8
When deploying in Kubernetes I get the following error on Spring Boot startup:
2019-01-02 13:41:41.462 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$e13002af] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.1.RELEASE)
2019-01-02 13:41:41.940 INFO 1 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: ConfigMapPropertySource {name='configmap.demo.default'}
2019-01-02 13:41:41.942 INFO 1 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: SecretsPropertySource {name='secrets.demo.default'}
2019-01-02 13:41:42.030 INFO 1 --- [ main] com.example.demo.DemoApplication : The following profiles are active: kubernetes
2019-01-02 13:41:43.391 INFO 1 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=416ee750-8ebb-365d-9114-12b51acaa1e0
2019-01-02 13:41:43.490 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$e13002af] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-01-02 13:41:43.917 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-01-02 13:41:43.952 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-01-02 13:41:43.953 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.13
2019-01-02 13:41:43.969 INFO 1 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64:/usr/lib/jvm/java-1.8-openjdk/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2019-01-02 13:41:44.156 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-01-02 13:41:44.157 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2033 ms
2019-01-02 13:41:44.957 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-01-02 13:41:45.353 WARN 1 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'propertyChangeWatcher' defined in class path resource [org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration$ConfigReloadAutoConfigurationBeans.class]: Unsatisfied dependency expressed through method 'propertyChangeWatcher' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'configurationUpdateStrategy' defined in class path resource [org/springframework/cloud/kubernetes/config/reload/ConfigReloadAutoConfiguration$ConfigReloadAutoConfigurationBeans.class]: Unsatisfied dependency expressed through method 'configurationUpdateStrategy' parameter 2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.context.restart.RestartEndpoint' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2019-01-02 13:41:45.358 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2019-01-02 13:41:45.370 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-01-02 13:41:45.398 INFO 1 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-01-02 13:41:45.612 ERROR 1 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 2 of method configurationUpdateStrategy in org.springframework.cloud.kubernetes.config.reload.ConfigReloadAutoConfiguration$ConfigReloadAutoConfigurationBeans required a bean of type 'org.springframework.cloud.context.restart.RestartEndpoint' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'restartEndpoint' in 'RestartEndpointWithIntegrationConfiguration' not loaded because #ConditionalOnClass did not find required class 'org.springframework.integration.monitor.IntegrationMBeanExporter'
- Bean method 'restartEndpointWithoutIntegration' in 'RestartEndpointWithoutIntegrationConfiguration' not loaded because #ConditionalOnEnabledEndpoint no property management.endpoint.restart.enabled found so using endpoint default
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.cloud.context.restart.RestartEndpoint' in your configuration.
If I set spring.cloud.kubernetes.reload.enabled to false everything works and the configmap is read and put to use. Now my goal is to reload the configuration if the configmap changes but get the exception seen above. I can invoke /actuator/refresh manually so I don't think it is the lack of the availability for the refresh endpoint.
I created a demo project with all included at https://drive.google.com/open?id=1QbP8vePALLZ2hWQJArnyxrzSySuXHKiz .
It starts if you set management.endpoint.restart.enabled=true
The message tells you that it can't load a RestartEndpoint bean. None was created because there's two ways it could be loaded and nether was satisfied:
Bean method 'restartEndpoint' in 'RestartEndpointWithIntegrationConfiguration' not loaded because #ConditionalOnClass did not find required class 'org.springframework.integration.monitor.IntegrationMBeanExporter'
Well you're not using spring integration so I guess you don't want this path - you want the other one.
Bean method 'restartEndpointWithoutIntegration' in 'RestartEndpointWithoutIntegrationConfiguration' not loaded because #ConditionalOnEnabledEndpoint no property management.endpoint.restart.enabled found so using endpoint default
So we need to set management.endpoint.restart.enabled=true, which is also set in the official reload example project. Without setting this the RestartEndpoint bean that we require will not be loaded.
In the application.properties add these two lines:
management.endpoint.restart.enabled=true
spring.jmx.enabled=true

Hibernate Validation does not look up error messages in a Spring boot application

This is my Spring boot project set up.
I have a standard Spring boot JPA stack in which I am trying to validate the state of the instance variables. My bean is as follows:
Configuration
#Component
public class ConfigurationHelper {
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public Validator validator() {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
factoryBean.setValidationMessageSource(this.messageSource());
return factoryBean;
}
}
Model class
#Table(name = "user_station", indexes = {
#Index(columnList = "station_id", name = "station_index_station_id"),
#Index(columnList = "station_name", name="station_index_name"),
#Index(columnList = "hd_enabled", name = "station_index_hd_enabled")
})
#Entity
#EqualsAndHashCode(exclude = {"createdTimeStamp", "updatedTimestamp"}, callSuper = true)
#ToString(exclude = {"createdTimeStamp", "updatedTimestamp"}, callSuper = true)
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Station extends IError {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#JsonIgnore
private Long id;
// Represents a station id for the user.
#Column(name="station_id", nullable = false, unique = true)
#NotEmpty(message = "{station.id.empty}")
#Pattern(regexp = "^K|W[A-Za-z0-9\\-].*$", message = "{station.id.name.not.valid}")
private String stationId;
#Column(name="station_name", nullable = false)
#JsonProperty("name")
#NotEmpty(message = "{station.name.empty}")
private String stationName;
#Column(name = "hd_enabled")
private Boolean hdEnabled;
#Column(name="call_sign", nullable = false)
#NotEmpty(message = "{station.call.sign.empty}")
private String callSign;
#Column(name="user_created_timestamp")
#JsonIgnore
private LocalDateTime createdTimeStamp;
#Column(name="user_modified_timestamp")
#JsonIgnore
private LocalDateTime updatedTimestamp;
/**
* Initialises the timestamps prior to update or insertions.
*
* <p>The implementation ensures that time stamps would always reflect the time when entities
* were persisted or updated.
*/
#PrePersist
#PreUpdate
public void setTimestamps() {
LocalDateTime utcNow = LocalDateTime.now(ZoneOffset.UTC);
if (this.createdTimeStamp == null) {
this.createdTimeStamp = utcNow;
}
this.updatedTimestamp = utcNow;
if (this.hdEnabled == null) {
this.hdEnabled = Boolean.FALSE;
}
}
// Getters, Setters, Equals and HashCode functions.
}
Unit tests
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes= {App.class})
public class StationTest {
#Autowired
private Validator validator;
private Station station;
#Before
public void setUp() throws Exception {
this.station = new Station();
}
#Test
public void testValidator_allNulls() {
Set<ConstraintViolation<Station>> constraintViolations =
this.validator.validate(this.station);
MatcherAssert.assertThat(constraintViolations.isEmpty(), Is.is(false));
for (ConstraintViolation<Station> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getMessage());
}
}
}
This is my output
. . . . Rest of the stack trace omitted . . . .
2018-12-01 23:30:38.532 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : Starting StationTest on Kartiks-MacBook-Pro-2.local with PID 21297 (started by krishnanand in /Users/krishnanand/projects/iheartmedia)
2018-12-01 23:30:38.533 DEBUG 21297 --- [ main] com.iheartmedia.model.StationTest : Running with Spring Boot v2.0.5.RELEASE, Spring v5.0.9.RELEASE
2018-12-01 23:30:38.539 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : No active profile set, falling back to default profiles: default
2018-12-01 23:30:38.596 INFO 21297 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 23:30:38 PST 2018]; root of context hierarchy
2018-12-01 23:30:39.565 INFO 21297 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b7d31eab] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-12-01 23:30:39.730 INFO 21297 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-12-01 23:30:39.871 INFO 21297 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-12-01 23:30:39.903 INFO 21297 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-12-01 23:30:39.917 INFO 21297 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-12-01 23:30:40.030 INFO 21297 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.17.Final}
2018-12-01 23:30:40.031 INFO 21297 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-12-01 23:30:40.066 INFO 21297 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-12-01 23:30:40.196 INFO 21297 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-12-01 23:30:40.652 INFO 21297 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-12-01 23:30:40.985 INFO 21297 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2018-12-01 23:30:41.351 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.586 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 23:30:38 PST 2018]; root of context hierarchy
2018-12-01 23:30:41.624 WARN 21297 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : 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
2018-12-01 23:30:41.658 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/stations],methods=[GET]}" onto public java.util.List<com.iheartmedia.model.Station> com.iheartmedia.controller.StationController.retrieveAllStations()
2018-12-01 23:30:41.660 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/station],methods=[POST]}" onto public org.springframework.http.ResponseEntity<com.iheartmedia.dto.StationMixin> com.iheartmedia.controller.StationController.createStation(com.iheartmedia.model.Station,org.springframework.validation.Errors)
2018-12-01 23:30:41.660 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/station],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<com.iheartmedia.dto.StationMixin> com.iheartmedia.controller.StationController.deleteStation(com.iheartmedia.model.Station)
2018-12-01 23:30:41.663 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-12-01 23:30:41.664 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-12-01 23:30:41.687 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.687 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.979 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : Started StationTest in 3.704 seconds (JVM running for 4.431)
{station.call.sign.empty}
{station.name.empty}
{station.id.empty}
2018-12-01 22:11:10.360 INFO 18663 --- [ Thread-2] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 22:11:06 PST 2018]; root of context hierarchy
2018-12-01 22:11:10.363 INFO 18663 --- [ Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-12-01 22:11:10.364 INFO 18663 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-12-01 22:11:10.367 INFO 18663 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 0
messages.properties Resource bundle
station.not.found=Station {0} was not found
station.id.empty=Station ID can not be empty.
station.id.format.not.valid=Station ID ${validatedValue} is not valid. Station ID should start with either W or K.
station.name.empty=Station name can not be empty.
station.call.sign.empty=Station call sign can not be empty.
Our dependency tree
I have read the following
Custom error messaging on Hibernate Validation
Custom Message Key in Hibernate validator not working with message.property
Does Spring Boot automatically resolve message keys in javax and hibernate validation annotations
but I can not still figure out what I am doing wrong.
UPDATE
Upon #Jonathan Johx's suggestion, I changed the basename of the ResourceBundleMessage to messages (Updated the code snippet as well), but I still get the error.
The issue is because the classpath: does reference to root of folder which is ConfigurationHelper class, it's not found. Try to rename file name to ValidationMessages.properties which is used by Validator and update the following line:
messageSource.setBasenames("ValidationMessages");
UPDATED
If you want to use validation messages by default then you have to create a file called:
ValidationMessages.properties
And add properties that you consider necessary.

Resources