How to turn off debug log messages in spring boot - spring

I read in spring boot docs (https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html)
you can also specify debug=true in your application.properties"
So I guess I can turn off the debug logs by adding debug=false in application.properties. I did it but unfortunately, it didn't work. Then I read in the same doc
The logging system is initialized early in the application lifecycle and as such logging properties will not be found in property files loaded via #PropertySource annotations"
and
"Since logging is initialized before the ApplicationContext is created, it isn’t possible to control logging from #PropertySources in Spring #Configuration files"
and
"When possible we recommend that you use the -spring variants for your logging configuration" so I added a file named log4j-spring.properties in src/main/resources.
In such file, I added debug=false (only this line and nothing else) but I am still seeing all "current date" [main] DEBUG ... messages. So, my question is how can I turn off the debug messages in my Spring Boot Application as I will deploy to the application to production. Is there a recommended way to reach this via maven?
Added in Feb 12th
The two main methods:
1)By using AnnotationConfigApplicationContext:
public class DemoAppNoBoot {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
BatchConfiguration.class);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("job");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Snippet output:
08:26:18.713 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:26:18.744 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:26:18.744 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
08:26:18.947 [main] INFO o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#532760d8: startup date [Fri Feb 12 08:26:18 CST 2016]; root of context hierarchy
08:26:18.947 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Bean factory for org.springframework.context.annotation.AnnotationConfigApplicationContext#532760d8: org.springframework.beans.factory.support.DefaultListableBeanFactory#50b494a6: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,batchConfiguration]; root of factory hierarchy
08:26:18.979 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean
...
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
08:26:32.560 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor'
08:26:32.560 [main] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor - Could not find default TaskScheduler bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:372) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
...
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL update
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL statement [UPDATE BATCH_JOB_EXECUTION set START_TIME = ?, END_TIME = ?, STATUS = ?, EXIT_CODE = ?, EXIT_MESSAGE = ?, VERSION = ?, CREATE_TIME = ?, LAST_UPDATED = ? where JOB_EXECUTION_ID = ? and VERSION = ?]
08:26:33.529 [pool-1-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - SQL update affected 1 rows
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Initiating transaction commit
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Committing JDBC transaction on Connection [org.hsqldb.jdbc.JDBCConnection#33bbce9c]
08:26:33.545 [pool-1-thread-1] DEBUG o.s.j.d.DataSourceTransactionManager - Releasing JDBC Connection [org.hsqldb.jdbc.JDBCConnection#33bbce9c] after transaction
08:26:33.545 [pool-1-thread-1] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
08:26:33.545 [pool-1-thread-1] INFO o.s.b.c.l.support.SimpleJobLauncher - Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Main method with SpringApplication.run
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(BatchConfiguration.class, args);
}
}
Entire output:
: Spring Boot :: (v1.3.1.RELEASE)
2016-02-12 08:02:36.145 INFO 12172 --- [ main] com.example.DemoApplication : Starting DemoApplication on GH-VDIKCISV252 with PID 12172 (C:\STS\wsRestTemplate\demo\target\classes started by e049447 in C:\STS\wsRestTemplate\demo)
2016-02-12 08:02:36.145 INFO 12172 --- [ main] com.example.DemoApplication : No active profile set, falling back to default profiles: default
2016-02-12 08:02:36.473 INFO 12172 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#4e4aea35: startup date [Fri Feb 12 08:02:36 CST 2016]; root of context hierarchy
2016-02-12 08:02:42.176 WARN 12172 --- [ 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.
2016-02-12 08:02:42.349 WARN 12172 --- [ 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.
2016-02-12 08:02:42.724 INFO 12172 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
2016-02-12 08:02:43.802 WARN 12172 --- [ main] o.s.b.c.l.AbstractListenerFactoryBean : org.springframework.batch.item.ItemReader is an interface. The implementing class will not be queried for annotation based listener configurations. If using #StepScope on a #Bean method, be sure to return the implementing class so listner annotations can be used.
2016-02-12 08:02:44.990 INFO 12172 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2016-02-12 08:02:45.179 INFO 12172 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 189 ms.
2016-02-12 08:02:46.804 INFO 12172 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-02-12 08:02:46.868 INFO 12172 --- [ main] o.s.b.a.b.JobLauncherCommandLineRunner : Running default command line with: []
2016-02-12 08:02:46.962 INFO 12172 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-02-12 08:02:47.040 INFO 12172 --- [pool-2-thread-1] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-02-12 08:02:47.243 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-02-12 08:02:47.259 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-02-12 08:02:47.321 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{run.id=1}]
2016-02-12 08:02:47.368 INFO 12172 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-02-12 08:02:47.400 INFO 12172 --- [ main] com.example.CustomItemReader : read method - collecting the MYAPP2 out file names
2016-02-12 08:02:47.525 INFO 12172 --- [ main] com.example.CustomItemReader : read method - no file found
2016-02-12 08:02:47.556 INFO 12172 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
2016-02-12 08:02:47.556 INFO 12172 --- [ main] com.example.DemoApplication : Started DemoApplication in 12.1 seconds (JVM running for 13.405)
2016-02-12 08:02:47.556 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{}]
2016-02-12 08:02:47.618 INFO 12172 --- [pool-2-thread-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-02-12 08:02:47.634 INFO 12172 --- [pool-2-thread-1] com.example.CustomItemReader : read method - collecting the MYAPP2 out file names
2016-02-12 08:02:47.634 INFO 12172 --- [pool-2-thread-1] com.example.CustomItemReader : read method - no file found
2016-02-12 08:02:47.650 INFO 12172 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]
BatchConfiguration class
#Configuration
#ComponentScan("com.example")
#EnableBatchProcessing
#EnableAutoConfiguration
#EnableScheduling
#PropertySource("config.properties")
public class BatchConfiguration {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Bean
public Step step1(ItemReader<String> reader,
ItemProcessor<String, String> processor, ItemWriter<String> writer) {
return stepBuilderFactory.get("step1").<String, String> chunk(1) .reader(reader).processor(processor).writer(writer)
.allowStartIfComplete(true).build();
}
//I took out the rest of BatchConfiguration class
Application.properties (only one line)
logging.level.*=OFF
P.S. I will not show config.properties because it only contains several property names with path settup used in business logic
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring.batch.version>3.0.6.RELEASE</spring.batch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.example.DemoAppNoBoot</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<goals>install</goals>
<preparationGoals>install</preparationGoals>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.example.DemoAppNoBoot</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
Maven Dependencies (the relevant ones for my doubt):
logback-classic-1.1.3.jar
logback-core-1.1.3.jar
slf4j-api-1.7.13.jar
log4j-over-slf4j-1.7.13.jar

In application.properties you can add ‘logging.level.*=LEVEL’ where ‘LEVEL’ is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. * is responsible for package/class.
For example
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
This means that root logger has WARN level.
org.springframework.web is on DEBUG level, but all hibernates files are logged only ERROR.
In your case you must set logging.level.root on one of level from INFO, WARN, ERROR,FATAL or OFF to turn off all logging.
See https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#boot-features-custom-log-levels

While using Spring Rest Docs with SpringMockMVC with testLogging.showStandardStreams set to true in Gradle, Spring cluttered the console with info & debug logs. I had to use Mkyong's solution where in a logback-test.xml in src/test/resources needs to be created on top of the chosen solution here. Use log-level OFF, ERROR, WARN, DEBUG
logback-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework" level="ERROR"/>
</configuration>

in addition to a log4j.properties or log4j.xml file you will need all three of these entries in your maven pom.xml... adding the log4j-acl artifact instantly fixed the problem for me. it routes apache-commons-logging entries from commons logging over to log4j
I'm not sure how you would go about this in grunt but the bridge is what you need.
<!-- Log4J -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
<version>${log4j.version}</version>
</dependency>

Simply add these two lines to you app main:
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.ERROR);
The necessary import are:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;

I am using XML configured Log4j2 and Spring Boot. For me, I needed to specify the logging subpackage also, so inside the <Loggers> block:
<Logger name="org.springframework.boot.autoconfigure.logging" level="error" />

You can also use bellow pattern to see the neat logging results in Console.
logging.pattern.console=%clr(%d{yy-MM-dd E HH:mm:ss.SSS}){blue} %clr(%-5p) %clr(%logger{0}){blue} %clr(%m){faint}%n

Click Breakpoints icon and untick checkBox. After Done Re-Run again

Related

Spring boot does not automatically create database tables on Mysql

First I already went over some solution on stacks but they did not work. I make a very basic/learning app on spring / mysql, no tables joining for the moment. The problem is tables are not creating on mysql, while everything is working. I copy my code hereunder.
Thanks in advance for the help
Console:
2021-06-15 11:25:07.895 INFO 8464 --- [ main]
c.j.v.VotingsystemApplication : Starting
VotingsystemApplication using Java 15.0.2 on LAPTOP-BQ48GM36 with PID
8464 (C:\Users\The Kash\Downloads\votingsystem\target\classes started
by The Kash in C:\Users\The Kash\Downloads\votingsystem)
2021-06-15 11:25:07.898 INFO 8464 --- [ main]
c.j.v.VotingsystemApplication : No active profile set,
falling back to default profiles: default
2021-06-15 11:25:08.734 INFO 8464 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules
found, entering strict repository configuration mode!
2021-06-15 11:25:08.736 INFO 8464 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JDBC repositories in DEFAULT mode.
2021-06-15 11:25:08.749 INFO 8464 --- [ main] .s.d.
r.c.RepositoryConfigurationDelegate : Finished Spring Data repository
scanning in 6 ms. Found 0 JDBC repository interfaces.
2021-06-15 11:25:08.760 INFO 8464 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules
found, entering strict repository configuration mode!
2021-06-15 11:25:08.762 INFO 8464 --- [ main] .s.d.
r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA
repositories in DEFAULT mode.
2021-06-15 11:25:08.769 INFO 8464 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data
repository scanning in 1 ms. Found 0 JPA repository interfaces.
2021-06-15 11:25:09.628 INFO 8464 --- [ main]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with
port(s): 8080 (http)
2021-06-15 11:25:09.640 INFO 8464 --- [ main]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-06-15 11:25:09.640 INFO 8464 --- [ main]
org.apache.catalina.core.StandardEngine : Starting Servlet engine:
[Apache Tomcat/9.0.46]
2021-06-15 11:25:09.776 INFO 8464 --- [ main] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring embedded
WebApplicationContext
2021-06-15 11:25:09.776 INFO 8464 --- [ main]
w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext:
initialization completed in 1808 ms
2021-06-15 11:25:09.924 INFO 8464 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-06-15 11:25:10.415 INFO 8464 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start
completed.
2021-06-15 11:25:10.582 INFO 8464 --- [ main]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default]
2021-06-15 11:25:10.672 INFO 8464 --- [ main]
org.hibernate.Version : HHH000412: Hibernate ORM
core version 5.4.32.Final
2021-06-15 11:25:10.879 INFO 8464 --- [ main]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.1.2.Final}
2021-06-15 11:25:11.018 INFO 8464 --- [ main]
org.hibernate.dialect.Dialect : HHH000400: Using dialect:
org.hibernate.dialect.MySQL5Dialect
2021-06-15 11:25:11.260 INFO 8464 --- [ main]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform
implementation:
[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-06-15 11:25:11.272 INFO 8464 --- [ main]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2021-06-15 11:25:11.322 WARN 8464 --- [ 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
2021-06-15 11:25:11.735 WARN 8464 --- [ main]
ion$DefaultTemplateResolverConfiguration : Cannot find template
location: classpath:/templates/ (please add some templates or check
your Thymeleaf configuration)
2021-06-15 11:25:11.999 INFO 8464 --- [ main] o.s.b.
w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080
(http) with context path ''
2021-06-15 11:25:12.013 INFO 8464 --- [ main]
c.j.v.VotingsystemApplication : Started
VotingsystemApplication
in 4.595 seconds (JVM running for 5.166)
VotingsystemApplication.java (main app)
package com.javaenterprise.votingsystem;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class VotingsystemApplication {
public static void main(String[] args) {
SpringApplication.run(VotingsystemApplication.class, args);
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost/VotingSystem
spring.datasource.username=root
spring.datasource.password=rooting1
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect =
org.hibernate.dialect.MySQL5Dialect
Citizen.java
package com.javaenterprise.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "citizens")
public class Citizen {
#Id
#Column(name="id")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "citizen_name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Citizen(Long id, String name) {
super();
this.id = id;
this.name = name;
}
}
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.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.javaenterprise</groupId>
<artifactId>votingsystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>votingsystem</name>
<description>Voting system in sprin</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The main entry point of your application is in the com.javaenterprise.votingsystem package. This means that component and entity scanning will find classes in com.javaenterprise.votingsystem and any of its sub-packages. Your entities are in the com.javaenterprise.entity which isn't covered by this scanning.
You could solve the problem by renaming your com.javaenterprise.entity package to com.javaenterprise.votingsystem.entity. Alternatively, you can use #EntityScan to specify the packages that you want to be scanned for entities.
Use the following property:
spring.datasource.url=jdbc:mysql://localhost:3306/dbname?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=update
And Second, Please add a default constructor as well.
So ur entity class will become:
package com.javaenterprise.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "citizens")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Citizen {
#Id
#Column(name="id")
private Long id;
#Column(name = "citizen_name")
private String name;
}
Can you try implementing Serializable and add DEFAULT Constructor ?
You can use this in your application.properties file
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root/your username
spring.datasource.password= yourpassword
spring.datasource.url=jdbc:mysql://localhost:3306/kibria
#for mysql dialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql = true

No table is being created neither the RestController Url is working

please tell what I am doing wrong, the code is running with no errors but I am getting no tables or the working restcontroller url whatsoever
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.usere.entity.UserEntity;
#RestController
#RequestMapping("/usr")
public class Ucontroller {
#RequestMapping("/showall")
public UserEntity showall()
{
return new UserEntity("abc",29);
}
}
pojo or model for rest
import javax.persistence.*;
#Entity
#Table(name = "usrtbl")
public class UserEntity {
#Id
#GeneratedValue
private int uid;
#Column(name = "name")
private String usrname;
#Column(name = "age")
private int age;
public UserEntity(String string, int i) {
// TODO Auto-generated constructor stub
usrname=string;
age=i;
}
//getter setters omitted
}
the autogenerated class
#SpringBootApplication
public class UserEnittyApplication {
public static void main(String[] args) {
SpringApplication.run(UserEnittyApplication.class, args);
}
}
servlet initializer(auto generated)
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
return application.sources(UserEnittyApplication.class);
}
}
Pom.xml file
<?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.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.user</groupId>
<artifactId>UserEnitty</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>UserEnitty</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
----------------------------EOF------------------
application.properties
server.port=7777
spring.datasource.url = jdbc:mysql://localhost:3306/poncho
spring.datasource.username = root
spring.datasource.password = password
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect =
org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
spring.mvc.view.prefix=/view/ // I tried using a simple controller
spring.mvc.view.suffix=.jsp // it didn't work too.
console
2019-08-25 10:41:06.534 INFO 9608 --- [ main] com.usere.demo.UserEnittyApplication : No active profile set, falling back to default profiles: default
2019-08-25 10:41:08.997 INFO 9608 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-08-25 10:41:09.055 INFO 9608 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 37ms. Found 0 repository interfaces.
2019-08-25 10:41:09.925 INFO 9608 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d899bdb3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-08-25 10:41:10.761 INFO 9608 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 7777 (http)
2019-08-25 10:41:10.840 INFO 9608 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-08-25 10:41:10.841 INFO 9608 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-08-25 10:41:11.205 INFO 9608 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-08-25 10:41:11.206 INFO 9608 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4551 ms
2019-08-25 10:41:11.653 INFO 9608 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-08-25 10:41:12.147 INFO 9608 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-08-25 10:41:12.328 INFO 9608 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-08-25 10:41:12.533 INFO 9608 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.10.Final}
2019-08-25 10:41:12.537 INFO 9608 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-08-25 10:41:12.938 INFO 9608 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-08-25 10:41:13.309 INFO 9608 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-08-25 10:41:13.874 INFO 9608 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-08-25 10:41:14.769 INFO 9608 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-08-25 10:41:14.954 WARN 9608 --- [ 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
2019-08-25 10:41:15.610 INFO 9608 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 7777 (http) with context path ''
2019-08-25 10:41:15.618 INFO 9608 --- [ main] com.usere.demo.UserEnittyApplication : Started UserEnittyApplication in 9.922 seconds (JVM running for 13.859)```
Create a repository class and call it for example UserEntityRepository like this:
public interface UserEntityRepository extends JpaRepository<UserEntity, Integer> {
}
Now create a service class and call it UserEntityService like this:
public interface PlayerService {
List<UserEntity> findAll();
Player findById(int theId);
void save(UserEntity theUserEntity);
void deleteById(int theId);
}
You don't necessarily need all these methods but these are common used crud methods.
Then you need to create a class that implements your service class for example:
#Service
public class UserEntityServiceImpl implements UserEntityService {
private UserEntityRepository userEntityRepository;
#Autowired
public CompanyBlueprintServiceImpl(UserEntityRepository theUserEntityRepository ) {
userEntityRepository= theUserEntityRepository ;
}
...
#Override
public void save(UserEntity theUserEntity) {
userEntityRepository.save(theUserEntity);
}
}
After doing all this you have to use your UserEntityService in your controller class. So you can call the save() method from your service to save your entity in your db.
#RestController
#RequestMapping("/api")
public class Ucontroller {
private UserEntityService userEntityService;
public Ucontroller(UserEntityService theUserEntityService) {
userEntityService = theUserEntityService;
}
#RequestMapping("/showall")
public UserEntity showall()
{
return new UserEntity("abc",29);
}
#PostMapping("/users")
public UserEntity addUser(#RequestBody UserEntity theUserEntity) {
// just in case an id in JSON was pass ... set id to 0
// this is to force a save of new item ... instead of update
theUserEntity.setUid(0);
userEntityService.save(theUserEntity);
return theCompany;
}
}
What you did is just creating a UserEntity object and returning it in your controller method showAll().
After saving the userEntity you should see the row in your db.
I am sorry to bother but I did a great mistake, the project package wasn't named correctlyenter image description here
you see the default generated package is com.usere.demo, earlier I named the other packages as com.usere.controller/entity which was wrong and we shouldn't do that, I thought it might not be important to post the package name, that said the correct name should be com.usere.demo.[anything you desire], thank you Constantin Beer and BaDr Amer for helping instantly and telling the right convention and workflow but it was a very stupid mistake that I made.

SpringCloud-Finchley.SR2 Eureka register-center page status 404

I imported a springcloud demo , version Finchley.SR2, after starting the application,I couldn't visit Eureka register center page,status 404.
I don't have and controller yet,Only a #SpringBootApplication
Same problem on eclipse and Idea
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Apr 17 10:46:08 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
If I use version Finchley.SR1 with dependency jersey-bundle 1.19, everything is normal.
Here is the 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 http://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.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>groupId</groupId>
<artifactId>register-center</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>register-center</name>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19</version>
</dependency>
-->
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
here is the starting log that console output:
2019-04-17 10:45:55.070 INFO 6608 --- [ main] c.g.c.h.HubRegisterCenterApplication : No active profile set, falling back to default profiles: default
2019-04-17 10:45:55.930 WARN 6608 --- [ main] o.s.boot.actuate.endpoint.EndpointId : Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2019-04-17 10:45:56.189 INFO 6608 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=b735a91d-6156-3751-9e56-6f2bcdd0ff57
2019-04-17 10:45:56.294 INFO 6608 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$e5276a08] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-04-17 10:45:56.982 INFO 6608 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8761 (http)
2019-04-17 10:45:57.007 INFO 6608 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-04-17 10:45:57.007 INFO 6608 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-17 10:45:57.277 INFO 6608 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-04-17 10:45:57.277 INFO 6608 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2190 ms
2019-04-17 10:45:57.390 WARN 6608 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2019-04-17 10:45:57.390 INFO 6608 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-04-17 10:45:57.408 INFO 6608 --- [ main] c.netflix.config.DynamicPropertyFactory : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration#4af70944
2019-04-17 10:45:58.631 WARN 6608 --- [ main] o.s.c.n.a.ArchaiusAutoConfiguration : No spring.application.name found, defaulting to 'application'
2019-04-17 10:45:58.632 WARN 6608 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2019-04-17 10:45:58.632 INFO 6608 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-04-17 10:45:58.854 INFO 6608 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-17 10:45:59.276 WARN 6608 --- [ main] o.s.b.a.f.FreeMarkerAutoConfiguration : Cannot find template location(s): [classpath:/templates/] (please add some templates, check your FreeMarker configuration, or set spring.freemarker.checkTemplateLocation=false)
2019-04-17 10:45:59.470 INFO 6608 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-04-17 10:45:59.716 INFO 6608 --- [ main] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING
2019-04-17 10:45:59.756 INFO 6608 --- [ main] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1
2019-04-17 10:45:59.758 INFO 6608 --- [ main] com.netflix.discovery.DiscoveryClient : Client configured to neither register nor query for data.
2019-04-17 10:45:59.775 INFO 6608 --- [ main] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1555469159773 with initial instances count: 0
2019-04-17 10:45:59.781 INFO 6608 --- [ main] o.s.c.n.e.s.EurekaServiceRegistry : Registering application UNKNOWN with eureka with status UP
2019-04-17 10:45:59.840 INFO 6608 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8761 (http) with context path ''
2019-04-17 10:45:59.844 INFO 6608 --- [ main] c.g.c.h.HubRegisterCenterApplication : Started HubRegisterCenterApplication in 6.441 seconds (JVM running for 7.261)
2019-04-17 10:46:08.612 INFO 6608 --- [nio-8761-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-04-17 10:46:08.612 INFO 6608 --- [nio-8761-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-04-17 10:46:08.618 INFO 6608 --- [nio-8761-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 6 ms
Here is my application.yml:
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
Here is my Application class:
#SpringBootApplication
#EnableEurekaServer
public class HubRegisterCenterApplication {
public static void main(String[] args) {
SpringApplication.run(HubRegisterCenterApplication.class, args);
}
}
Problem solved.
use mvn install command,and I found that there is some problems in maven dependency jar file. delete them and re-download,problem solved
Use application.properties file instead of application.yml file.
like
spring.application.name=cart-service
server.port=8082
It worked for me.

Spring Boot controller returns 404 for all api endpoints

I am new to Spring's ecosystem. And I am stuck with this particular situation. My application server responds with 404 for all of my API endpoints.
This is my controller
package com.example.controllers;
import com.example.models.Movie;
import com.example.services.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
#RestController
public class MovieController {
#Autowired
private MovieService movieService;
#RequestMapping(value = "/movies", method = RequestMethod.GET)
#ResponseBody
public List<Movie> getAllMovies(){
return movieService.getAllMovies();
}
#RequestMapping(value = "/movies", method = RequestMethod.POST)
#ResponseBody
public Movie addNewMovie(#RequestBody Movie movie){
System.out.println("Hello World");
return movieService.addMovie(movie);
}
#RequestMapping(value = "/movies/{id}", method = RequestMethod.GET)
#ResponseBody
public Optional<Movie> getMovieById(#PathVariable String id){
return movieService.getMovieById(id);
}
#RequestMapping(value = "/movies", method = RequestMethod.PUT)
#ResponseBody
public Movie updateMovie(#RequestBody Movie movie){
return movieService.updateMovie(movie);
}
#RequestMapping(value = "/movies/{id}", method = RequestMethod.DELETE)
public void removeMovieById(#PathVariable String id){
movieService.deleteMovie(id);
}
}
And this my main class
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#EnableAutoConfiguration
#ComponentScan
#SpringBootApplication
public class LearnSpringApplication{
public static void main(String[] args) {
SpringApplication.run(LearnSpringApplication.class, args);
}
}
I am running it on localhost and port is 8080. I did set up a small app prior to this one, and that worked as expected. However, I am guessing that it's because the controller is in a different package since in the previous app, the main class and the controller were in the same package.
Edit Here's my pom.xml file:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>learn_spring</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>learn_spring</name>
<description>Project to learn Spring</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
EDIT My Spring-Boot startup logs are
2018-05-03 17:16:44.937 INFO 14017 --- [ main] com.example.LearnSpringApplication : Starting LearnSpringApplication v0.0.1 on tfc with PID 14017 (/home/ayush/Workspace/learn_spring/target/learn_spring-0.0.1.jar started by ayush in /home/ayush/Workspace/learn_spring)
2018-05-03 17:16:44.940 INFO 14017 --- [ main] com.example.LearnSpringApplication : No active profile set, falling back to default profiles: default
2018-05-03 17:16:45.045 INFO 14017 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#6aba2b86: startup date [Thu May 03 17:16:45 IST 2018]; root of context hierarchy
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (jar:file:/home/ayush/Workspace/learn_spring/target/learn_spring-0.0.1.jar!/BOOT-INF/lib/spring-core-5.0.5.RELEASE.jar!/) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2018-05-03 17:16:46.113 INFO 14017 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-05-03 17:16:46.138 INFO 14017 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-05-03 17:16:46.139 INFO 14017 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-05-03 17:16:46.151 INFO 14017 --- [ost-startStop-1] 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/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib]
2018-05-03 17:16:46.218 INFO 14017 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-05-03 17:16:46.218 INFO 14017 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1186 ms
2018-05-03 17:16:46.336 INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-05-03 17:16:46.339 INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-03 17:16:46.340 INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-03 17:16:46.340 INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-03 17:16:46.340 INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-03 17:16:46.455 INFO 14017 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:46.720 INFO 14017 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#6aba2b86: startup date [Thu May 03 17:16:45 IST 2018]; root of context hierarchy
2018-05-03 17:16:46.786 INFO 14017 --- [ 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-05-03 17:16:46.787 INFO 14017 --- [ 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-05-03 17:16:46.817 INFO 14017 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:46.817 INFO 14017 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:47.060 INFO 14017 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-05-03 17:16:47.151 INFO 14017 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:12}] to localhost:27017
2018-05-03 17:16:47.155 INFO 14017 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 3]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=null, roundTripTimeNanos=2192957}
2018-05-03 17:16:47.323 INFO 14017 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-05-03 17:16:47.392 INFO 14017 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-05-03 17:16:47.395 INFO 14017 --- [ main] com.example.LearnSpringApplication : Started LearnSpringApplication in 2.89 seconds (JVM running for 3.296)
Sometimes is because of your package structure. Always make sure your controllers are in same package or sub-package level as the #SpringBootApplication class.
For example:
If application class is at com.a.b then controllers should be at com.a.b or com.a.b.c or com.a.b.c.d etc. You don't always have to add #ComponentScan to get them registered.
You're using IntelliJ IDEA community version, which does not support the Spring Framework:
see https://www.jetbrains.com/idea/features/editions_comparison_matrix.html for reference
Update
Since you're using the command line, then the above does not apply. I'll leave it here as a reference, though.
In the comments, you have specified that when running mvn clean package followed by java -jar target/whatever-your-project-name-is.jar, you get the following error:
Field movieService in com.example.controllers.MovieController required a bean of type 'com.example.services.MovieService' that could not be found.
Please make sure that:
you have a class MovieService in the package services
that class is annotated with the #Service annotation
Update 2
Since the above did not work, try replacing
#ComponentScan
by
#ComponentScan({"com.example.services", "com.example.controllers"})
in your LearnSpringApplication class.
Include all other packages that have classes annotated with #Component, #Service, #Controller, #RestController, or #Repository.
Note that this is a workaround. Normally, having #ComponentScan alone should be sufficient -- or as #DarrenForsythe mentionned in the comment, even just #SpringBootApplication should be sufficient for your case.
I had the same problem today and tried the simple solution provided above by #Daniel Moshi. It worked fine. Thanks.
Other option is using like below:
#SpringBootApplication(scanBasePackages = "com.example")
...with this the Controller can stay in any sub-package of com.example and works good even without explicit usage of #ComponentScan.

Spting cloud data flow batch job is running one time if #EnableTask is used in main app

Hi I am trying to deploy simple spring boot batch jar file in local spring cloud data flow server. I am facing serious problem in the batch when I am using #EnableTask in my main java class. When I am using #EnableTask in my application the batch job is running only one time. Its executing the batch and then de registering the application automatically. Code for the application is given below.
1)main class
package com.jwt.spring.batch;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.task.configuration.EnableTask;
#EnableTask
#EnableBatchProcessing
#SpringBootApplication
public class ScdfBatchApplication {
public static void main(String[] args) {
SpringApplication.run(ScdfBatchApplication.class, args);
}
}
2)JobConfiguration.java
package com.jwt.spring.batch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
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.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class JobConfiguration {
private static final Log logger = LogFactory.getLog(JobConfiguration.class);
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
public Job job() {
return jobBuilderFactory.get("job").start(stepBuilderFactory.get("jobStep1").tasklet(new Tasklet() {
#Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
logger.info("Job was run");
return RepeatStatus.FINISHED;
}
}).build()).build();
}
}
3)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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jwt.spring.batch</groupId>
<artifactId>SCDFBatch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SCDFBatch</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud-task.version>1.2.2.RELEASE</spring-cloud-task.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-task</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-dependencies</artifactId>
<version>${spring-cloud-task.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Below is the log of the application
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.9.RELEASE)
2018-01-05 17:13:37.984 INFO 14436 --- [ main] c.jwt.spring.batch.ScdfBatchApplication : Starting ScdfBatchApplication on bdc7-l-5065XBS with PID 14436 (C:\STS-WORK_SPACE\SPRING-BATCH\SCDFBatch\target\classes started by mukesh.bo.kumar in C:\STS-WORK_SPACE\SPRING-BATCH\SCDFBatch)
2018-01-05 17:13:37.990 INFO 14436 --- [ main] c.jwt.spring.batch.ScdfBatchApplication : No active profile set, falling back to default profiles: default
2018-01-05 17:13:38.091 INFO 14436 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#9e725a: startup date [Fri Jan 05 17:13:38 IST 2018]; root of context hierarchy
2018-01-05 17:13:39.153 INFO 14436 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'transactionManager' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.cloud.task.configuration.SimpleTaskConfiguration; factoryMethodName=transactionManager; initMethodName=null; destroyMethodName=(inferred); defined in org.springframework.cloud.task.configuration.SimpleTaskConfiguration] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration; factoryMethodName=transactionManager; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class]]
2018-01-05 17:13:39.784 WARN 14436 --- [ 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.
2018-01-05 17:13:39.804 WARN 14436 --- [ 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.
2018-01-05 17:13:39.943 INFO 14436 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration' of type [org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration$$EnhancerBySpringCGLIB$$e6554726] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-01-05 17:13:39.952 INFO 14436 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$60e59b9a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-01-05 17:13:40.005 INFO 14436 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.task.batch.listener.BatchEventAutoConfiguration' of type [org.springframework.cloud.task.batch.listener.BatchEventAutoConfiguration$$EnhancerBySpringCGLIB$$2eab5129] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-01-05 17:13:40.955 INFO 14436 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-01-05 17:13:40.971 INFO 14436 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-01-05 17:13:40.972 INFO 14436 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2018-01-05 17:13:41.201 INFO 14436 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-01-05 17:13:41.202 INFO 14436 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3116 ms
2018-01-05 17:13:41.540 INFO 14436 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-01-05 17:13:41.544 INFO 14436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-01-05 17:13:41.545 INFO 14436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-01-05 17:13:41.545 INFO 14436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-01-05 17:13:41.545 INFO 14436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-01-05 17:13:42.681 INFO 14436 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/cloud/task/schema-h2.sql]
2018-01-05 17:13:42.726 INFO 14436 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/cloud/task/schema-h2.sql] in 45 ms.
2018-01-05 17:13:43.076 INFO 14436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#9e725a: startup date [Fri Jan 05 17:13:38 IST 2018]; root of context hierarchy
2018-01-05 17:13:43.170 INFO 14436 --- [ 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.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-01-05 17:13:43.172 INFO 14436 --- [ 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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-01-05 17:13:43.206 INFO 14436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-05 17:13:43.207 INFO 14436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-05 17:13:43.314 INFO 14436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-05 17:13:43.415 INFO 14436 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-h2.sql]
2018-01-05 17:13:43.435 INFO 14436 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-h2.sql] in 20 ms.
2018-01-05 17:13:43.592 INFO 14436 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-01-05 17:13:43.603 INFO 14436 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2018-01-05 17:13:43.721 INFO 14436 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-01-05 17:13:43.725 INFO 14436 --- [ main] o.s.b.a.b.JobLauncherCommandLineRunner : Running default command line with: []
2018-01-05 17:13:43.730 INFO 14436 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: H2
2018-01-05 17:13:43.913 INFO 14436 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2018-01-05 17:13:43.961 INFO 14436 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job]] launched with the following parameters: [{}]
2018-01-05 17:13:43.972 INFO 14436 --- [ main] o.s.c.t.b.l.TaskBatchExecutionListener : The job execution id 1 was run within the task execution 1
2018-01-05 17:13:43.981 INFO 14436 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [jobStep1]
2018-01-05 17:13:43.992 INFO 14436 --- [ main] com.jwt.spring.batch.JobConfiguration : Job was run
2018-01-05 17:13:43.998 INFO 14436 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job]] completed with the following parameters: [{}] and the following status: [COMPLETED]
2018-01-05 17:13:44.003 INFO 14436 --- [ main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#9e725a: startup date [Fri Jan 05 17:13:38 IST 2018]; root of context hierarchy
2018-01-05 17:13:44.004 INFO 14436 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 0
2018-01-05 17:13:44.005 INFO 14436 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2018-01-05 17:13:44.278 INFO 14436 --- [ main] c.jwt.spring.batch.ScdfBatchApplication : Started ScdfBatchApplication in 6.956 seconds (JVM running for 9.208)
Please this post. You need to use the RunIdIncrementer in your job.
Spring Batch Item Reader is executing only once
First thing Please add timestamp to name of the Job to make it unique everytime its being run.
Secondly, you should use task-launcher or stream to launch your task run more than once.
Launch it using TriggerTask; with this you could either choose to launch it with fixedDelay or via a cron expression
Finally if you wanted job to be running based on some event then create and deploy your spring batch job as stream rather than deploying as task. What type of stream depends upon your requirement whether it is processor or sink. As per the details in your query, its more kind of processor hence reference examples from spring cloud stream related to processor, have pasted a sample processor application code.
Please refer https://github.com/spring-cloud/spring-cloud-stream-samples/tree/master/transform

Resources