spring batch ItemWriter creating output twice - spring

I have written a spring batch job which reads from a db and then write to a csv.
The job is pretty simple and it works HOWEVER the ItemWriter looks like it is being executed twice. i.e. I am ending up with two CSV's (exactly the same), instead of one.
Can someone help me work out why please? It does so with a different jobExecution.id.
Attaching batch job and console output of run below...
#Configuration
#EnableBatchProcessing
public class ExportMasterListCsvJobConfig {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
public Job exportMasterListCsvJob(
Step readStgDbAndExportMasterListStep,
Step writeToCsvStep) {
return jobBuilderFactory.get("exportMasterListCsvJob")
.incrementer(new RunIdIncrementer())
.flow(readStgDbAndExportMasterListStep)
.end()
.build();
}
#Bean
public Step readStgDbAndExportMasterListStep(
#Value("${exportMasterListCsv.generateMasterListRows.chunkSize}") int chunkSize,
#Qualifier("queryOnlineStagingDbReader") ItemReader<MasterList> queryOnlineStagingDbReader,
#Qualifier("masterListFileWriter") ItemWriter<MasterList> masterListFileWriter) {
return stepBuilderFactory.get("readStgDbAndExportMasterListStep")
.<MasterList,MasterList>chunk(chunkSize)
.reader(queryOnlineStagingDbReader)
.writer(masterListFileWriter)
.build();
}
#Bean
public ItemReader<MasterList> queryOnlineStagingDbReader(
DataSource onlineStagingDb,
#Value("${exportMasterListCsv.generateMasterListRows.masterListSql}") String masterListSql) {
JdbcCursorItemReader<MasterList> reader = new JdbcCursorItemReader<>();
reader.setDataSource(onlineStagingDb);
reader.setSql(masterListSql);
reader.setRowMapper(new RowMapper<MasterList>() {
#Override
public MasterList mapRow(ResultSet resultSet, int i) throws SQLException {
MasterList masterList = new MasterList();
masterList.setL2(resultSet.getString("l2"));
masterList.setL2Name(resultSet.getString("l2_name"));
return masterList;
}
});
return reader;
}
#Bean
#StepScope
public ItemWriter<MasterList> masterListFileWriter(
FileSystemResource masterListFile,
#Value("#{stepExecutionContext}")Map<String, Object> executionContext) {
FlatFileItemWriter<MasterList> writer = new FlatFileItemWriter<>();
writer.setResource(masterListFile);
DelimitedLineAggregator<MasterList> lineAggregator = new DelimitedLineAggregator<>();
lineAggregator.setDelimiter(",");
BeanWrapperFieldExtractor<MasterList> extractor = new BeanWrapperFieldExtractor<MasterList>();
extractor.setNames(new String[] { "l2", "l2Name"});
lineAggregator.setFieldExtractor(extractor);
writer.setLineAggregator(lineAggregator);
writer.setForceSync(true);
writer.open(new ExecutionContext(executionContext));
return writer;
}
#Bean
#JobScope
public FileSystemResource masterListFile(
#Value("${temp.dir}") String tempDir,
#Value("#{jobExecution.id}") Long jobId
) throws IOException {
return new FileSystemResource(new File(tempDir, "masterList" + jobId + ".csv"));
}
}
And Console Output...
13:03:45.815 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.827 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
13:03:45.836 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
13:03:45.853 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest] from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
13:03:45.884 [main] DEBUG org.springframework.test.context.support.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#3cbbc1e0 declaringClass = 'com.myer.pricing.onlinestore.export.ExportMasterListCsvTest', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
13:03:45.899 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]: class path resource [com/myer/pricing/onlinestore/export/ExportMasterListCsvTest-context.xml] does not exist
13:03:45.900 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]: class path resource [com/myer/pricing/onlinestore/export/ExportMasterListCsvTestContext.groovy] does not exist
13:03:45.900 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]: no resource found for suffixes {-context.xml, Context.groovy}.
13:03:45.927 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.boot.test.IntegrationTestPropertiesListener#724af044, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#4678c730, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#6767c1fc, org.springframework.test.context.support.DirtiesContextTestExecutionListener#29ee9faa, org.springframework.test.context.transaction.TransactionalTestExecutionListener#c038203, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#cc285f4]
13:03:45.931 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.931 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.946 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.946 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.948 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.948 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.950 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.950 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.953 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#6a4f787b testClass = ExportMasterListCsvTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#685cb137 testClass = ExportMasterListCsvTest, locations = '{}', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', contextInitializerClasses = '[]', activeProfiles = '{batchtest}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
13:03:45.954 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.954 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myer.pricing.onlinestore.export.ExportMasterListCsvTest]
13:03:45.959 [main] DEBUG org.springframework.test.util.ReflectionTestUtils - Getting field 'mergedContextConfiguration' from target object [[DefaultTestContext#6a4f787b testClass = ExportMasterListCsvTest, testInstance = com.myer.pricing.onlinestore.export.ExportMasterListCsvTest#53b32d7, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#685cb137 testClass = ExportMasterListCsvTest, locations = '{}', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', contextInitializerClasses = '[]', activeProfiles = '{batchtest}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]]] or target class [class org.springframework.test.context.support.DefaultTestContext]
13:03:45.960 [main] DEBUG org.springframework.test.util.ReflectionTestUtils - Setting field 'propertySourceProperties' of type [null] on target object [[MergedContextConfiguration#685cb137 testClass = ExportMasterListCsvTest, locations = '{}', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', contextInitializerClasses = '[]', activeProfiles = '{batchtest}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]] or target class [class org.springframework.test.context.MergedContextConfiguration] to value [[Ljava.lang.String;#4667ae56]
13:03:45.961 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext#6a4f787b testClass = ExportMasterListCsvTest, testInstance = com.myer.pricing.onlinestore.export.ExportMasterListCsvTest#53b32d7, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#685cb137 testClass = ExportMasterListCsvTest, locations = '{}', classes = '{class com.myer.pricing.onlinestore.export.TestJobConfig, class com.myer.pricing.onlinestore.export.job.ExportMasterListCsvJobConfig}', contextInitializerClasses = '[]', activeProfiles = '{batchtest}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.IntegrationTest=true}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]]].
13:03:46.072 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
13:03:46.073 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
13:03:46.074 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
13:03:46.074 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [test] PropertySource with highest search precedence
13:03:46.075 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [integrationTest] PropertySource with search precedence immediately lower than [systemEnvironment]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.6.RELEASE)
2016-07-22 13:03:46.541 INFO 10084 --- [ main] c.m.p.o.export.ExportMasterListCsvTest : Starting ExportMasterListCsvTest on IGSM473537 with PID 10084 (C:\design_centre_dev\myer-pricing-engine\java-onlinestore-feed-exporter\target\test-classes started by rriviere in C:\design_centre_dev\myer-pricing-engine\java-onlinestore-feed-exporter)
2016-07-22 13:03:46.542 INFO 10084 --- [ main] c.m.p.o.export.ExportMasterListCsvTest : The following profiles are active: batchtest
2016-07-22 13:03:46.875 INFO 10084 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#4e08711f: startup date [Fri Jul 22 13:03:46 AEST 2016]; root of context hierarchy
2016-07-22 13:03:48.151 INFO 10084 --- [ main] o.s.b.f.config.PropertiesFactoryBean : Loading properties file from URL [jar:file:/C:/.m2/repository/org/springframework/integration/spring-integration-core/4.2.8.RELEASE/spring-integration-core-4.2.8.RELEASE.jar!/META-INF/spring.integration.default.properties]
2016-07-22 13:03:48.157 INFO 10084 --- [ main] o.s.i.config.IntegrationRegistrar : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2016-07-22 13:03:48.716 WARN 10084 --- [ 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-07-22 13:03:48.728 WARN 10084 --- [ 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-07-22 13:03:48.742 INFO 10084 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
2016-07-22 13:03:48.751 INFO 10084 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
2016-07-22 13:03:48.900 INFO 10084 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$402d705e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-07-22 13:03:49.060 INFO 10084 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
2016-07-22 13:03:49.459 INFO 10084 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [db/sql/staging_db.sql]
2016-07-22 13:03:49.465 INFO 10084 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [db/sql/staging_db.sql] in 6 ms.
2016-07-22 13:03:49.710 WARN 10084 --- [ main] o.s.b.c.l.AbstractListenerFactoryBean : org.springframework.batch.item.ItemWriter 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-07-22 13:03:49.797 INFO 10084 --- [ main] o.s.aop.framework.CglibAopProxy : Unable to proxy method [public final java.lang.String org.springframework.core.io.FileSystemResource.getPath()] because it is final: All calls to this method via a proxy will NOT be routed to the target instance.
2016-07-22 13:03:50.236 INFO 10084 --- [ main] o.s.b.f.config.PropertiesFactoryBean : Loading properties file from URL [jar:file:/C:/.m2/repository/org/springframework/integration/spring-integration-core/4.2.8.RELEASE/spring-integration-core-4.2.8.RELEASE.jar!/META-INF/spring.integration.default.properties]
2016-07-22 13:03:50.730 INFO 10084 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
2016-07-22 13:03:51.258 INFO 10084 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2016-07-22 13:03:51.281 INFO 10084 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 23 ms.
2016-07-22 13:03:51.813 INFO 10084 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2016-07-22 13:03:51.814 INFO 10084 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2016-07-22 13:03:51.814 INFO 10084 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'application:batchtest.errorChannel' has 1 subscriber(s).
2016-07-22 13:03:51.814 INFO 10084 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started _org.springframework.integration.errorLogger
2016-07-22 13:03:51.832 INFO 10084 --- [ main] o.s.b.a.b.JobLauncherCommandLineRunner : Running default command line with: []
2016-07-22 13:03:51.844 INFO 10084 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-07-22 13:03:51.973 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-07-22 13:03:52.044 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=exportMasterListCsvJob]] launched with the following parameters: [{run.id=1}]
2016-07-22 13:03:52.073 INFO 10084 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [readStgDbAndExportMasterListStep]
2016-07-22 13:03:52.167 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=exportMasterListCsvJob]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
2016-07-22 13:03:52.169 INFO 10084 --- [ main] c.m.p.o.export.ExportMasterListCsvTest : Started ExportMasterListCsvTest in 6.091 seconds (JVM running for 6.895)
2016-07-22 13:03:52.196 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=exportMasterListCsvJob]] launched with the following parameters: [{random=93853}]
2016-07-22 13:03:52.234 INFO 10084 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [readStgDbAndExportMasterListStep]
2016-07-22 13:03:52.290 INFO 10084 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=exportMasterListCsvJob]] completed with the following parameters: [{random=93853}] and the following status: [COMPLETED]
2016-07-22 13:03:52.305 INFO 10084 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#4e08711f: startup date [Fri Jul 22 13:03:46 AEST 2016]; root of context hierarchy
2016-07-22 13:03:52.307 INFO 10084 --- [ Thread-1] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 0
2016-07-22 13:03:52.308 INFO 10084 --- [ Thread-1] o.s.i.endpoint.EventDrivenConsumer : Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2016-07-22 13:03:52.309 INFO 10084 --- [ Thread-1] o.s.i.channel.PublishSubscribeChannel : Channel 'application:batchtest.errorChannel' has 0 subscriber(s).
2016-07-22 13:03:52.309 INFO 10084 --- [ Thread-1] o.s.i.endpoint.EventDrivenConsumer : stopped _org.springframework.integration.errorLogger
2016-07-22 13:03:52.314 INFO 10084 --- [ Thread-1] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'taskScheduler'
2016-07-22 13:03:52.317 INFO 10084 --- [ Thread-1] o.s.j.d.e.EmbeddedDatabaseFactory : Shutting down embedded database: url='jdbc:hsqldb:mem:testdb'
And this produces two CSV's each with a different jobExecution.id which I have appended to the file name. masterList0.csv AND masterList1.csv
thanks in advance

I had the following setting in my yml file...
spring:
batch:
job.enabled: true
This was causing my job to run twice. After changing it to false it fixed my problem.

Related

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.

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

Spring Boot JPA multiple datasource error

I wanted to connect my spring boot app to 2 databases . So according to a tutorial i created 2 config classes.
Config Class 1
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:database-configs.properties" })
#EnableJpaRepositories(
basePackages = {"com.dialog.pod.ideabiz_admin.data_access_objects"},
entityManagerFactoryRef = "adminEntityManagerFactory",
transactionManagerRef = "adminTransactionManager")
public class IdeabizAdminConfig {
#Autowired
private Environment env;
#Bean
PlatformTransactionManager adminTransactionManager() {
return new JpaTransactionManager(adminEntityManagerFactory().getObject());
}
#Bean
LocalContainerEntityManagerFactoryBean adminEntityManagerFactory() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
// jpaVendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(adminDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setPackagesToScan("com.dialog.pod.ideabiz_admin.models");
factoryBean.setJpaPropertyMap(jpaProperties());
factoryBean.setPersistenceUnitName("adminDataSource");
return factoryBean;
}
#Bean
DataSource adminDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("admin.jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("admin.jdbc.url"));
dataSource.setUsername(env.getProperty("admin.jdbc.username"));
dataSource.setPassword(env.getProperty("admin.jdbc.password"));
return dataSource;
}
private Map<String, Object> jpaProperties() {
Map<String, Object> props = new HashMap<>();
props.put("hibernate.implicit_naming_strategy","org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl");
props.put("hibernate.physical_naming_strategy","com.dialog.pod.PhysicalNamingStrategyImpl");
return props;
}
}
Config Class 2
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:database-configs.properties" })
#EnableJpaRepositories(
basePackages = {"com.dialog.pod.ideabiz_log_summary.data_access_objects"},
entityManagerFactoryRef = "sumLogEntityManagerFactory",
transactionManagerRef = "sumLogTransactionManager")
public class IdeabizLogSummaryConfig {
#Autowired
private Environment env;
#Bean
PlatformTransactionManager sumLogTransactionManager() {
return new JpaTransactionManager(sumLogEntityManagerFactory().getObject());
}
#Bean
LocalContainerEntityManagerFactoryBean sumLogEntityManagerFactory() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
// jpaVendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(adminDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setPackagesToScan("com.dialog.pod.ideabiz_log_summary.models");
factoryBean.setJpaPropertyMap(jpaProperties());
factoryBean.setPersistenceUnitName("sumLogDataSource");
return factoryBean;
}
#Bean
DataSource adminDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("sumlog.jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("sumlog.jdbc.url"));
dataSource.setUsername(env.getProperty("sumlog.jdbc.username"));
dataSource.setPassword(env.getProperty("sumlog.jdbc.password"));
return dataSource;
}
private Map<String, Object> jpaProperties() {
Map<String, Object> props = new HashMap<>();
props.put("hibernate.implicit_naming_strategy","org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl");
props.put("hibernate.physical_naming_strategy","com.dialog.pod.PhysicalNamingStrategyImpl");
return props;
}
}
Application Class
#SpringBootApplication
#EnableAutoConfiguration (exclude = { DataSourceAutoConfiguration.class })
#Configuration
#ComponentScan
public class PodApiApplication {
public static void main(String[] args) {
SpringApplication.run(PodApiApplication.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/").allowedOrigins("*");
}
};
}
}
When i try to run the app i get following error.
***************************
APPLICATION FAILED TO START
***************************
Description:
Method requestMappingHandlerMapping in org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration required a single bean, but 2 were found:
- adminEntityManagerFactory: defined by method 'adminEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]
- sumLogEntityManagerFactory: defined by method 'sumLogEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]
Action:
Consider marking one of the beans as #Primary, updating the consumer to accept multiple beans, or using #Qualifier to identify the bean that should be consumed
Process finished with exit code 1
I put #Primary to the first config class(according to another tutorial). When i do that datasource in the first config class works. Problem is when i do this first datasource also applied to all the jparepositories.
I'm new to Spring boot. I have been trying to solve this problem for over 5 hours :( . Thanks in advance for any help you are able to provide.
Full Log
2017-01-27 00:52:39.713 INFO 6704 --- [ main] com.dialog.pod.PodApiApplication : Starting PodApiApplication on DESKTOP-4B89ITN with PID 6704 (started by y2ksh in H:\Spring MVC Workspace\platform-overview-dashboard\PODApi)
2017-01-27 00:52:39.718 INFO 6704 --- [ main] com.dialog.pod.PodApiApplication : No active profile set, falling back to default profiles: default
2017-01-27 00:52:39.938 INFO 6704 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6e171cd7: startup date [Fri Jan 27 00:52:39 IST 2017]; root of context hierarchy
2017-01-27 00:52:41.712 INFO 6704 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'adminDataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=ideabizAdminConfig; factoryMethodName=adminDataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=ideabizLogSummaryConfig; factoryMethodName=adminDataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]]
2017-01-27 00:52:42.804 INFO 6704 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$3cc0fc3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-01-27 00:52:43.594 INFO 6704 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8081 (http)
2017-01-27 00:52:43.609 INFO 6704 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-01-27 00:52:43.609 INFO 6704 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.6
2017-01-27 00:52:43.810 INFO 6704 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-01-27 00:52:43.810 INFO 6704 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3891 ms
2017-01-27 00:52:44.247 INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-01-27 00:52:44.253 INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'metricFilter' to: [/*]
2017-01-27 00:52:44.254 INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-01-27 00:52:44.254 INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-01-27 00:52:44.254 INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-01-27 00:52:44.254 INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-01-27 00:52:44.255 INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2017-01-27 00:52:44.255 INFO 6704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'applicationContextIdFilter' to: [/*]
2017-01-27 00:52:44.367 INFO 6704 --- [ main] o.s.j.d.DriverManagerDataSource : Loaded JDBC driver: com.mysql.jdbc.Driver
2017-01-27 00:52:44.403 INFO 6704 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:44.435 INFO 6704 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: adminDataSource
...]
2017-01-27 00:52:44.634 INFO 6704 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.11.Final}
2017-01-27 00:52:44.636 INFO 6704 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-01-27 00:52:44.641 INFO 6704 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-01-27 00:52:44.725 INFO 6704 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-01-27 00:52:45.302 INFO 6704 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-01-27 00:52:46.178 INFO 6704 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:46.189 INFO 6704 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:46.190 INFO 6704 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: sumLogDataSource
...]
2017-01-27 00:52:46.228 INFO 6704 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-01-27 00:52:46.291 INFO 6704 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:46.695 INFO 6704 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2017-01-27 00:52:46.947 INFO 6704 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2017-01-27 00:52:47.496 INFO 6704 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6e171cd7: startup date [Fri Jan 27 00:52:39 IST 2017]; root of context hierarchy
2017-01-27 00:52:47.560 WARN 6704 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]: Factory method 'requestMappingHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openEntityManagerInViewInterceptor' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 2: adminEntityManagerFactory,sumLogEntityManagerFactory
2017-01-27 00:52:47.562 INFO 6704 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'sumLogDataSource'
2017-01-27 00:52:47.563 INFO 6704 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'adminDataSource'
2017-01-27 00:52:47.566 INFO 6704 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2017-01-27 00:52:47.586 INFO 6704 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-01-27 00:52:47.592 ERROR 6704 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Method requestMappingHandlerMapping in org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration required a single bean, but 2 were found:
- adminEntityManagerFactory: defined by method 'adminEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_admin/IdeabizAdminConfig.class]
- sumLogEntityManagerFactory: defined by method 'sumLogEntityManagerFactory' in class path resource [com/dialog/pod/ideabiz_log_summary/IdeabizLogSummaryConfig.class]
Action:
Consider marking one of the beans as #Primary, updating the consumer to accept multiple beans, or using #Qualifier to identify the bean that should be consumed
Process finished with exit code 1
Mark one of the beans as primary
#Primary
#Bean
public EntityManagerFactory entityManagerFactory() {
}
Your Spring Boot application implicitly activates Spring Web Mvc via #WebMvcAutoConfiguration which is triggered by having, among others, Servlet.class in your class path. This #WebMvcAutoConfiguration requires a bean of type EntityManagerFactory. However, you have registered two such beans adminEntityManagerFactory and sumLogEntityManagerFactory. So you have to tell Spring Web Mvc which is your preferred one via #Primary on top of the respective #Bean method. Alternatively if you don't need Web Mvc autoconfiguration switch it off by #EnableAutoConfiguration(exclude={WebMvcAutoConfiguration}) and configure Web Mvc manually.
It turns out i used same method name for both datasource beans . This was the reason why only one data source used for all jparepos. Thanks #Javatar81 for explaining how bean naming works

AspectJ LTW not working with Spring Boot on unmanaged classes

I'm facing a problem on a large scale application using SpringBoot and AspectJ for logging purposes. The logging works fine for Spring Beans, but does not work for unmanaged classes (the ones I instantiate with 'new').
I've created a sample app where you can see the problem happening, you can access it here:
https://bitbucket.org/tomkro/stack_question
The application is pretty simple, the Gradle file is a common with the standard Spring Boot starters.
There are 5 relevant classes here.
Application.java, which is the main class:
#EnableAspectJAutoProxy
#EnableLoadTimeWeaving(aspectjWeaving= EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
#SpringBootApplication(scanBasePackages = "com.test.*")
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
The AspectConfig file (which for the sake of simplicity also defines the RestController, could be easily separated files)
#RestController
#Configuration
#ComponentScan(basePackages = {"com.test"})
public class AspectConfig {
#Bean
public TestLogger testLogger(){
return new TestLogger();
}
#Autowired
TestClass testClass;
#RequestMapping("/")
public int get() {
return testClass.methodFromClass1();
}
}
The TestLogger, which defines the aspect for this app:
#Aspect
public class TestLogger {
public TestLogger() {
}
#Around("execution( * com.test.classes..*.*(..))")
public Object aroundExecution(ProceedingJoinPoint pjp) throws Throwable {
String packageName = pjp.getSignature().getDeclaringTypeName();
String methodName = pjp.getSignature().getName();
long start = System.currentTimeMillis();
System.out.println(packageName + "." + methodName + " - Starting execution ");
Object output = pjp.proceed();
Long elapsedTime = System.currentTimeMillis() - start;
System.out.println(packageName + "." + methodName + " - Ending execution ["+elapsedTime+" ms]");
return output;
}
}
And then there's two files, one managed by Spring, the other not:
TestClass1:
#Component
public class TestClass {
public int methodFromClass1() {
TestClass2 test = new TestClass2();
return test.methodFromClass2();
}
}
TestClass2
public class TestClass2 {
public int methodFromClass2() {
int a = 10;
int b = 5;
return b + a;
}
}
Also there's the aop.xml file in META-INF which specifies the Aspect
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver option="-debug">
<!-- only weave classes in our application-specific packages -->
<include within="com.test.*"/>
</weaver>
<aspects>
<!-- weave in just this aspect -->
<aspect name="com.test.utilities.TestLogger"/>
</aspects>
</aspectj>
I followed most of this build using the tutorial on the Spring documentation here , and I've been scratching my head for two days now and I can't figure out what's happening. The managed Bean logs fine, but the unmanaged one is not being logged.
I'm using the run.bat included in the project for starting, basically it does this:
call gradle build
java -javaagent:.\src\main\resources\aspectjweaver.jar -javaagent:.\src\main\resources\spring-instrument.jar -jar build\libs\Test-0.0.1-SNAPSHOT.jar
Both jars are the latest. Usually you only would need of the JAR's, but I saw someone using both and gave it a shot. This is the output after startup and execution of a call to "localhost:8080"
[LaunchedURLClassLoader#6d8a00e3] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.0.RELEASE)
2016-04-08 15:21:44.116 INFO 20400 --- [ main] com.test.Application : Starting Application on PC000BR23205 with PID 20400 (C:\git\Test\build\libs\Test-0.0.1-SNAPSHOT.jar started by tkroth in C:\git\T
est)
2016-04-08 15:21:44.120 INFO 20400 --- [ main] com.test.Application : No profiles are active
2016-04-08 15:21:44.294 INFO 20400 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2cd72cea: startup date [Fri Ap
r 08 15:21:44 BRT 2016]; root of context hierarchy
2016-04-08 15:21:44.950 INFO 20400 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver' 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.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; fa
ctoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]]
with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$W
ebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAut
oConfigurationAdapter.class]]
2016-04-08 15:21:45.872 INFO 20400 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-04-08 15:21:45.888 INFO 20400 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-04-08 15:21:45.891 INFO 20400 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.28
2016-04-08 15:21:45.987 INFO 20400 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-04-08 15:21:45.987 INFO 20400 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1695 ms
2016-04-08 15:21:46.342 INFO 20400 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-04-08 15:21:46.347 INFO 20400 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-04-08 15:21:46.348 INFO 20400 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-04-08 15:21:46.349 INFO 20400 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-04-08 15:21:46.349 INFO 20400 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-04-08 15:21:46.439 INFO 20400 --- [ main] o.s.c.w.DefaultContextLoadTimeWeaver : Found Spring's JVM agent for instrumentation
2016-04-08 15:21:46.455 INFO 20400 --- [ main] o.s.c.w.DefaultContextLoadTimeWeaver : Found Spring's JVM agent for instrumentation
[LaunchedURLClassLoader#6d8a00e3] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
2016-04-08 15:21:46.781 INFO 20400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2cd72cea:
startup date [Fri Apr 08 15:21:44 BRT 2016]; root of context hierarchy
2016-04-08 15:21:46.874 INFO 20400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public int com.test.configuration.AspectConfig.get()
2016-04-08 15:21:46.877 INFO 20400 --- [ 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.sp
ringframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-04-08 15:21:46.878 INFO 20400 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoco
nfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2016-04-08 15:21:46.912 INFO 20400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-08 15:21:46.912 INFO 20400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-04-08 15:21:47.030 INFO 20400 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler
]
2016-04-08 15:21:47.133 INFO 20400 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-04-08 15:21:47.204 INFO 20400 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-04-08 15:21:47.210 INFO 20400 --- [ main] com.test.Application : Started Application in 3.481 seconds (JVM running for 4.306)
2016-04-08 15:21:51.680 INFO 20400 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-04-08 15:21:51.680 INFO 20400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2016-04-08 15:21:51.704 INFO 20400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 23 ms
com.test.classes.TestClass.methodFromClass1 - Starting execution
com.test.classes.TestClass.methodFromClass1 - Ending execution [15 ms]
As you can see, TestClass2 is never logged, although it's called. What am I missing here?
The real question is, how can I make non-beans to be handled by LTW in a SpringBoot environment? Feel free to commit changes on the repository I provided above.

spring boot tempory h2 database table empty in junit4 test

I am using Spring Boot 1.2.5 and want to do some JUnit4 testing. I have an Eclipse project that contains the test. During initializiation a temporay H2 database is created. I have a schema.xml and data.xml. The initialization is fine, but later three of 5 tables are empty.
First I had the database created by Spring boot. No code from my side, just the XML in the resources folder. This runs without any problems. Then I found that in the test three of the five tables are empty. The schema still exists, but not data.
I then changed to manual creation of the H2 database/datasource bean and in the same method I checked if all records are present. This made no difference in the test results. I could only show that just after creation the database is populated as expected. It seems that during bean creation and JUnit test some routine is doing a delete on three specific tables.
package de.unit4.financials;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.test.jdbc.JdbcTestUtils;
#SpringBootApplication
public class JUnitConfig {
Logger logger = LogManager.getLogger();
#Bean
public DataSource getDataSource() {
DataSource dataSource = null;
if (dataSource == null) {
dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).setName("FanUtilDB")
.addScript("classpath:schema.sql").addScript("classpath:data.sql").build();
}
logger.info("Datasource "+dataSource);
testDB(new JdbcTemplate(dataSource));
return dataSource;
}
public void testDB(JdbcTemplate jdbcTemplate) {
countTableRows("oas_company", jdbcTemplate);
countTableRows("oas_agm", jdbcTemplate);
countTableRows("oas_agmlist", jdbcTemplate);
countTableRows("com_usr", jdbcTemplate);
countTableRows("com_capab", jdbcTemplate);
}
private void countTableRows(String name, JdbcTemplate jdbcTemplate) {
int anzahl = JdbcTestUtils.countRowsInTable(jdbcTemplate, name);
logger.info(name + " = " + anzahl);
}
}
This is the output:
08:58:16.007 [main] INFO Datasource org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy#60094a13 || de.unit4.financials.JUnitConfig getDataSource 54
08:58:16.197 [main] INFO oas_company = 28 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.199 [main] INFO oas_agm = 2 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.201 [main] INFO oas_agmlist = 2 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.203 [main] INFO com_usr = 52 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.205 [main] INFO com_capab = 17 || de.unit4.financials.JUnitConfig countTableRows 74
Later the JUnit test is run and it gives me this result:
08:58:19.099 [main] INFO Datasource org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy#60094a13 || de.unit4.financials.periods.CurrentPeriodDBFactory getCurrentPeriod 63
08:58:19.127 [main] INFO oas_company = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.128 [main] INFO oas_agm = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.128 [main] INFO oas_agmlist = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.129 [main] INFO com_usr = 52 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.130 [main] INFO com_capab = 17 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
The DataSource object seems to be the same, but the record count is different. During the test, the first three are empty.
Here is the test:
package de.unit4.financials;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.jdbc.JdbcTestUtils;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = JUnitConfig.class)
public class FinancialsUtilApplicationTests {
static Logger logger = LogManager.getLogger();
#Autowired
JdbcTemplate jdbcTemplate;
#Test
public void contextLoads() {
}
#Test
public void testDB() {
countTableRows("oas_company");
countTableRows("oas_agm");
countTableRows("oas_agmlist");
countTableRows("com_usr");
countTableRows("com_capab");
}
/**
* #param name
*/
private void countTableRows(String name) {
int anzahl = JdbcTestUtils.countRowsInTable(jdbcTemplate, name);
logger.info(name + " = " + anzahl);
}
}
Here is the full console output:
08:58:12.555 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class de.unit4.financials.periods.PeriodRangeTest].
08:58:12.581 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
08:58:12.607 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#32e6e9c3 declaringClass = 'de.unit4.financials.periods.PeriodRangeTest', classes = '{class de.unit4.financials.JUnitConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
08:58:12.618 [main] DEBUG o.s.t.c.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.627 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - #TestExecutionListeners is not present for class [de.unit4.financials.periods.PeriodRangeTest]: using defaults.
08:58:12.644 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
08:58:12.672 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
08:58:12.688 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#73ad2d6, org.springframework.test.context.support.DirtiesContextTestExecutionListener#7085bdee, org.springframework.test.context.transaction.TransactionalTestExecutionListener#1ce92674, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#5700d6b1]
08:58:12.692 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.694 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.718 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class de.unit4.financials.periods.CurrentPeriodDBFactoryTest].
08:58:12.718 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
08:58:12.720 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#4566e5bd declaringClass = 'de.unit4.financials.periods.CurrentPeriodDBFactoryTest', classes = '{class de.unit4.financials.JUnitConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
08:58:12.721 [main] DEBUG o.s.t.c.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [de.unit4.financials.periods.CurrentPeriodDBFactoryTest]
08:58:12.722 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - #TestExecutionListeners is not present for class [de.unit4.financials.periods.CurrentPeriodDBFactoryTest]: using defaults.
08:58:12.727 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
08:58:12.729 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
08:58:12.729 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#2d928643, org.springframework.test.context.support.DirtiesContextTestExecutionListener#5025a98f, org.springframework.test.context.transaction.TransactionalTestExecutionListener#49993335, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#20322d26]
08:58:12.729 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.CurrentPeriodDBFactoryTest]
08:58:12.730 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.CurrentPeriodDBFactoryTest]
08:58:12.733 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class de.unit4.financials.periods.PeriodTest].
08:58:12.734 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
08:58:12.736 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#64bf3bbf declaringClass = 'de.unit4.financials.periods.PeriodTest', classes = '{class de.unit4.financials.JUnitConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
08:58:12.737 [main] DEBUG o.s.t.c.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [de.unit4.financials.periods.PeriodTest]
08:58:12.738 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - #TestExecutionListeners is not present for class [de.unit4.financials.periods.PeriodTest]: using defaults.
08:58:12.743 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
08:58:12.744 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
08:58:12.745 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#544fe44c, org.springframework.test.context.support.DirtiesContextTestExecutionListener#31610302, org.springframework.test.context.transaction.TransactionalTestExecutionListener#71318ec4, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#21213b92]
08:58:12.745 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodTest]
08:58:12.745 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodTest]
08:58:12.752 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class de.unit4.financials.FinancialsUtilApplicationTests].
08:58:12.753 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
08:58:12.762 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#3108bc declaringClass = 'de.unit4.financials.FinancialsUtilApplicationTests', classes = '{class de.unit4.financials.JUnitConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
08:58:12.762 [main] DEBUG o.s.t.c.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [de.unit4.financials.FinancialsUtilApplicationTests]
08:58:12.763 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - #TestExecutionListeners is not present for class [de.unit4.financials.FinancialsUtilApplicationTests]: using defaults.
08:58:12.769 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
08:58:12.770 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
08:58:12.770 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#335eadca, org.springframework.test.context.support.DirtiesContextTestExecutionListener#210366b4, org.springframework.test.context.transaction.TransactionalTestExecutionListener#eec5a4a, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#2b2948e2]
08:58:12.770 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.FinancialsUtilApplicationTests]
08:58:12.770 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.FinancialsUtilApplicationTests]
08:58:12.786 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.787 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.788 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.789 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.790 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.790 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.793 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.793 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:13.324 [main] DEBUG o.s.t.c.s.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext#6193932a testClass = PeriodRangeTest, testInstance = de.unit4.financials.periods.PeriodRangeTest#647fd8ce, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#159f197 testClass = PeriodRangeTest, locations = '{}', classes = '{class de.unit4.financials.JUnitConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]]].
08:58:13.395 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:58:13.398 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:58:13.398 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
08:58:13.401 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [integrationTest] PropertySource with search precedence immediately lower than [systemEnvironment]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.2.5.RELEASE)
2015-07-20 08:58:13.766 INFO 8552 --- [ main] d.u.financials.periods.PeriodRangeTest : Starting PeriodRangeTest on gsender with PID 8552 (C:\Users\gsender\Documents\workspace-libs\FinancialsUtility\target\test-classes started by GSender in C:\Users\gsender\Documents\workspace-libs\FinancialsUtility)
2015-07-20 08:58:13.812 INFO 8552 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#524d6d96: startup date [Mon Jul 20 08:58:13 CEST 2015]; root of context hierarchy
2015-07-20 08:58:15.572 INFO 8552 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Creating embedded database 'FanUtilDB'
2015-07-20 08:58:15.823 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [schema.sql]
2015-07-20 08:58:15.851 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [schema.sql] in 28 ms.
2015-07-20 08:58:15.851 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [data.sql]
2015-07-20 08:58:15.990 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [data.sql] in 139 ms.
08:58:16.007 [main] INFO Datasource org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy#60094a13 || de.unit4.financials.JUnitConfig getDataSource 54
08:58:16.197 [main] INFO oas_company = 28 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.199 [main] INFO oas_agm = 2 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.201 [main] INFO oas_agmlist = 2 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.203 [main] INFO com_usr = 52 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.205 [main] INFO com_capab = 17 || de.unit4.financials.JUnitConfig countTableRows 74
2015-07-20 08:58:16.271 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/C:/Users/gsender/Documents/workspace-libs/FinancialsUtility/target/test-classes/schema.sql]
2015-07-20 08:58:16.285 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/C:/Users/gsender/Documents/workspace-libs/FinancialsUtility/target/test-classes/schema.sql] in 14 ms.
2015-07-20 08:58:16.289 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/C:/Users/gsender/Documents/workspace-libs/FinancialsUtility/target/test-classes/data.sql]
2015-07-20 08:58:16.391 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/C:/Users/gsender/Documents/workspace-libs/FinancialsUtility/target/test-classes/data.sql] in 101 ms.
2015-07-20 08:58:16.555 INFO 8552 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2015-07-20 08:58:16.590 INFO 8552 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2015-07-20 08:58:16.682 INFO 8552 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {4.3.10.Final}
2015-07-20 08:58:16.684 INFO 8552 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2015-07-20 08:58:16.686 INFO 8552 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2015-07-20 08:58:16.979 INFO 8552 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2015-07-20 08:58:17.136 INFO 8552 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2015-07-20 08:58:17.424 INFO 8552 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2015-07-20 08:58:18.153 INFO 8552 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2015-07-20 08:58:18.178 INFO 8552 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2015-07-20 08:58:19.063 INFO 8552 --- [ main] d.u.financials.periods.PeriodRangeTest : Started PeriodRangeTest in 5.659 seconds (JVM running for 7.356)
08:58:19.099 [main] INFO Datasource org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy#60094a13 || de.unit4.financials.periods.CurrentPeriodDBFactory getCurrentPeriod 63
08:58:19.127 [main] INFO oas_company = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.128 [main] INFO oas_agm = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.128 [main] INFO oas_agmlist = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.129 [main] INFO com_usr = 52 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.130 [main] INFO com_capab = 17 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
2015-07-20 08:58:19.134 INFO 8552 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#524d6d96: startup date [Mon Jul 20 08:58:13 CEST 2015]; root of context hierarchy
2015-07-20 08:58:19.386 INFO 8552 --- [ Thread-1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2015-07-20 08:58:19.387 INFO 8552 --- [ Thread-1] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2015-07-20 08:58:19.398 INFO 8552 --- [ Thread-1] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
For Table creation I use (example):
drop table IF EXISTS oas_company;
CREATE TABLE IF NOT EXISTS oas_company (
code varchar(12) NOT NULL,
code_cs int NOT NULL,
For data inserts I use:
delete from oas_agm;
INSERT INTO oas_agm(code, tstamp, name, sname, adddate, deldate, moddate, usrname)
VALUES('U4SW-JUNIT-1', 1, 'Account Test Entwicklung', 'debit', '2015-07-15 00:00:00.0', NULL, '2015-07-15 15:31:39.0', 'INSTALL');
Thanks for any help on this confusing result.
I found the solution: Hibernate recreates the tables after initialisation (by Spring Boot). I added spring.jpa.hibernate.ddl-auto=none to application.properties and the problem was gone.
This is the first time this happened in a project. It is also unclear why only three out of five tables are recreated. At first I assumed it was due to an "old" database file, but then I switched from H2 to HSQL and the problem stayed. An error from Hibernate showed me the path to solution (unable to delete...).

Resources