spring boot tempory h2 database table empty in junit4 test - spring

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...).

Related

How to create an H2+flyway test database in spring boot?

I have a spring boot project where I want to test my controller.I use MySql database for production but want an in memory database for running the testcases.I use Flyway for versioning database migration.I want my test database to use the same versioning.Can someone please help me with a way to do that?
This is what my application.properties in src/test/resources folder looks like:
# Database Properties
spring.jpa.database=H2
spring.database.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL;INIT=CREATE SCHEMA IF NOT EXISTS public;DATABASE_TO_UPPER=false
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
security.basic.enabled:false
spring.datasource.username:sa
spring.datasource.password:
# Flyway Properties
spring.flyway.locations=filesystem:src/main/resources/db/migration
spring.flyway.enabled=true
spring.flyway.baseline-on-migrate=true
This is my Test File:
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
#ContextConfiguration
public class PermissionsControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void existentUserCanGetTokenAndAuthenticationAndAlsoExtractPermissions() throws Exception {
String username = "Srishti";
String body = "{" + "\"username\":\"" + username + "\"}";
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/authenticate")
.contentType(MediaType.APPLICATION_JSON_VALUE).content(body)).andDo(print()).andExpect(status().isOk())
.andReturn();
String response = result.getResponse().getContentAsString();
mockMvc.perform(MockMvcRequestBuilders.get("/permission").header("Authorization", "Bearer " + response))
.andExpect(status().isOk()).andDo(print()).andReturn();
mockMvc.perform(MockMvcRequestBuilders.get("/permission/9").header("Authorization", "Bearer " + response))
.andExpect(status().isOk()).andDo(print()).andReturn();
}
}
And this is the output that I get currently get:
2020-09-06 19:30:54.481 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : Starting PermissionsControllerTest on DGKDSQ13 with PID 26936 (started by SrishtiChawla in C:\Users\srishtichawla\Desktop\LCTraining\LCTraining)
2020-09-06 19:30:54.483 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : No active profile set, falling back to default profiles: default
2020-09-06 19:30:55.599 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-09-06 19:30:55.600 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2020-09-06 19:30:55.670 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.LOBRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.672 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.PermissionsRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.674 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.ProductCategoryRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.677 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.RolesRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.679 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.ScoringModelSuiteRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.681 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.UserRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.682 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 74ms. Found 0 JDBC repository interfaces.
2020-09-06 19:30:55.694 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-09-06 19:30:55.695 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-09-06 19:30:55.762 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 63ms. Found 6 JPA repository interfaces.
2020-09-06 19:30:56.308 INFO 26936 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler#1e5eb20a' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-09-06 19:30:56.325 INFO 26936 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-09-06 19:30:57.018 INFO 26936 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
2020-09-06 19:30:57.032 INFO 26936 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-09-06 19:30:57.033 INFO 26936 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-09-06 19:30:57.216 INFO 26936 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-09-06 19:30:57.216 INFO 26936 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2708 ms
2020-09-06 19:30:57.353 WARN 26936 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-09-06 19:30:57.509 INFO 26936 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.4.4 by Redgate
2020-09-06 19:30:57.515 INFO 26936 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-09-06 19:30:57.746 INFO 26936 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-09-06 19:30:57.773 INFO 26936 --- [ main] o.f.c.internal.database.DatabaseFactory : Database: jdbc:h2:mem:testdb (H2 1.4)
2020-09-06 19:30:57.864 INFO 26936 --- [ main] o.f.core.internal.command.DbValidate : Successfully validated 9 migrations (execution time 00:00.036s)
2020-09-06 19:30:57.883 INFO 26936 --- [ main] o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table "PUBLIC"."flyway_schema_history" ...
2020-09-06 19:30:57.955 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Current version of schema "PUBLIC": << Empty Schema >>
2020-09-06 19:30:57.970 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.1 - createTables
2020-09-06 19:30:58.100 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.2 - inservalues
2020-09-06 19:30:58.144 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.3 - altertable
2020-09-06 19:30:58.183 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.4 - INSERTVALUES2
2020-09-06 19:30:58.216 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.5 - insertvalues3
2020-09-06 19:30:58.241 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.6 - ALTERTABLE
2020-09-06 19:30:58.264 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.7 - Altertablelob
2020-09-06 19:30:58.293 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.8 - insertvals
2020-09-06 19:30:58.315 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.10 - uniquekey
2020-09-06 19:30:58.330 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Successfully applied 9 migrations to schema "PUBLIC" (execution time 00:00.383s)
2020-09-06 19:30:58.541 INFO 26936 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-06 19:30:58.639 INFO 26936 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-09-06 19:30:58.711 INFO 26936 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.18.Final
2020-09-06 19:30:58.903 INFO 26936 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-09-06 19:30:59.060 INFO 26936 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-09-06 19:30:59.320 INFO 26936 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2020-09-06 19:30:59.970 INFO 26936 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-09-06 19:30:59.982 INFO 26936 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-09-06 19:31:00.409 INFO 26936 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-09-06 19:31:00.489 INFO 26936 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#1c43e84e, org.springframework.security.web.context.SecurityContextPersistenceFilter#5e62ca19, org.springframework.security.web.header.HeaderWriterFilter#493968a9, org.springframework.web.filter.CorsFilter#7bd694a5, org.springframework.security.web.authentication.logout.LogoutFilter#322ab6ce, com.training.LCtraining.filter.JwtFilter#af9dd34, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#6528d339, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#3149409c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#21ce2e4d, org.springframework.security.web.session.SessionManagementFilter#780c0, org.springframework.security.web.access.ExceptionTranslationFilter#7a8b7e11, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#11ee671f]
2020-09-06 19:31:01.178 INFO 26936 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring TestDispatcherServlet ''
2020-09-06 19:31:01.179 INFO 26936 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2020-09-06 19:31:01.195 INFO 26936 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 16 ms
2020-09-06 19:31:01.298 INFO 26936 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 51516 (http) with context path ''
2020-09-06 19:31:01.300 INFO 26936 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-09-06 19:31:01.785 INFO 26936 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-09-06 19:31:01.801 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : Started PermissionsControllerTest in 7.711 seconds (JVM running for 9.214)
Hibernate: select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?
2020-09-06 19:31:02.278 WARN 26936 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42102, SQLState: 42S02
2020-09-06 19:31:02.279 ERROR 26936 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Table "user" not found; SQL statement:
select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=? [42102-200]
MockHttpServletRequest:
HTTP Method = POST
Request URI = /authenticate
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"22"]
Body = {"username":"Srishti"}
Session Attrs = {}
Handler:
Type = com.training.LCtraining.integration.UserRestController
Method = com.training.LCtraining.integration.UserRestController#generateToken(AuthRequest)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.dao.InvalidDataAccessResourceUsageException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"timestamp":"2020-09-06","message":"could not prepare statement; SQL [select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","details":"uri=/authenticate"}
Forwarded URL = null
Redirected URL = null
Cookies = []
MockHttpServletRequest:
HTTP Method = POST
Request URI = /authenticate
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"22"]
Body = {"username":"Srishti"}
Session Attrs = {}
Handler:
Type = com.training.training.integration.UserRestController
Method = com.training.training.integration.UserRestController#generateToken(AuthRequest)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.dao.InvalidDataAccessResourceUsageException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"timestamp":"2020-09-06","message":"could not prepare statement; SQL [select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","details":"uri=/authenticate"}
Forwarded URL = null
Redirected URL = null
Cookies = []
2020-09-06 19:31:02.656 INFO 26936 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-09-06 19:31:02.659 INFO 26936 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-09-06 19:31:02.659 INFO 26936 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-09-06 19:31:02.664 INFO 26936 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
The controllers are working fine on the production side.
This is my V1.1__createtable.sql file
create table permissions(
permissionID int not null auto_increment,
permissionTitle varchar(40) not null,
permissionDescription varchar(255),
PRIMARY KEY (permissionID),
UNIQUE (permissionTitle));
insert into permissions(permissionTitle) values('Create Role');
insert into permissions(permissionTitle) values('Edit Role');
insert into permissions(permissionTitle) values('Delete Role');
insert into permissions(permissionTitle) values('Create User');
insert into permissions(permissionTitle) values('Edit User');
insert into permissions(permissionTitle) values('Delete User');
insert into permissions(permissionTitle) values('Create LOB');
insert into permissions(permissionTitle) values('Edit LOB');
insert into permissions(permissionTitle) values('Delete LOB');
According to the logs, Flyway is executed successfully:
Flyway Community Edition 6.4.4 by Redgate
HikariPool-1 - Starting...
HikariPool-1 - Start completed.
Database: jdbc:h2:mem:testdb (H2 1.4)
Successfully validated 9 migrations (execution time 00:00.036s)
Creating Schema History table "PUBLIC"."flyway_schema_history" ...
Current version of schema "PUBLIC": << Empty Schema >>
Migrating schema "PUBLIC" to version 1.1 - createTables
Migrating schema "PUBLIC" to version 1.2 - inservalues
Migrating schema "PUBLIC" to version 1.3 - altertable
Migrating schema "PUBLIC" to version 1.4 - INSERTVALUES2
Migrating schema "PUBLIC" to version 1.5 - insertvalues3
Migrating schema "PUBLIC" to version 1.6 - ALTERTABLE
Migrating schema "PUBLIC" to version 1.7 - Altertablelob
Migrating schema "PUBLIC" to version 1.8 - insertvals
Migrating schema "PUBLIC" to version 1.10 - uniquekey
Successfully applied 9 migrations to schema "PUBLIC" (execution time 00:00.383s)
You can see that 9 migrations are applied: createTables, inservalues, altertable, INSERTVALUES2, insertvalues3, ALTERTABLE, Altertablelob, insertvals, uniquekey.
Is this list complete or are you expecting more migrations?
The error you see later in the log comes from Hibernate, not from Flyway.
And it says:
Table "user" not found
Looking the migration names, I would expect that the user table is created by the createTables migration. But there's no CREATE TABLE 'user' statement in V1.1__createTables.sql.
Please double-check that all necessary tables are defined in your migrations. You should NOT alter old migrations. Instead, you can create new migrations for the missing tables and use CREATE TABLE IF NOT EXISTS syntax, so that it's compatible with existing production environment.
I had a similar problem and my solution was described in a comment by #Srish. Changing my url from jdbc:h2:mem:[MYDB] to jdbc:h2:file:~/[MYDB] allowed flyway to successfully perform the migrations as well perform JPA's validation.

how execute and show friendly tests output when running gradle from command line

I can run easily my project tests from IntelliJ IDEA but I am struggling to run them and see the results running from command line.
I read several suggestions around and it seems the trick part is over here
tasks.test {
useJUnitPlatform()
}
tasks.withType<Test> {
this.testLogging {
this.showStandardStreams = true
}
}
As you can see from bellow image all tests are ran and I can see the result in IntelliJ
Neverthelless, when I try from Windows Command Line in same project I get
C:\WSs\KotlinGradleIntelliJ\jokenpo>gradlew test
> Task :test
JokenpoApplicationTests STANDARD_OUT
13:19:28.436 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
13:19:28.452 [Test worker] 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:19:28.467 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.mycomp.jokenpo.JokenpoApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
13:19:28.483 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.mycomp.jokenpo.JokenpoApplicationTests], using SpringBootContextLoader
13:19:28.498 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: class path resource [com/mycomp/jokenpo/JokenpoApplicationTests-context.xml] does not exist
13:19:28.498 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: class path resource [com/mycomp/jokenpo/JokenpoApplicationTestsContext.groovy] does not exist
13:19:28.498 [Test worker] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
13:19:28.498 [Test worker] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: JokenpoApplicationTests does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
13:19:28.552 [Test worker] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.mycomp.jokenpo.JokenpoApplicationTests]
13:19:28.621 [Test worker] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\WSs\KotlinGradleIntelliJ\jokenpo\build\classes\kotlin\main\com\mycomp\jokenpo\JokenpoApplication.class]
13:19:28.621 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found #SpringBootConfiguration com.mycomp.jokenpo.JokenpoApplication for test class com.mycomp.jokenpo.JokenpoApplicationTests
13:19:28.738 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - #TestExecutionListeners is not present for class [com.mycomp.jokenpo.JokenpoApplicationTests]: using defaults.
13:19:28.739 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
13:19:28.757 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#1f9e5479, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#7f837ef0, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#75d05b, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#532b090b, org.springframework.test.context.support.DirtiesContextTestExecutionListener#3efba28b, org.springframework.test.context.transaction.TransactionalTestExecutionListener#5a6b3f5a, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#7432cb44, org.springframework.test.context.event.EventPublishingTestExecutionListener#7f5ae798, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#1cd6ed02, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#1f44802d, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#7d4e106a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#55004e7c, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#7e951723]
13:19:28.762 [Test worker] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#7d4abcae testClass = JokenpoApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration#d073212 testClass = JokenpoApplicationTests, locations = '{}', classes = '{class com.mycomp.jokenpo.JokenpoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#4b3fa0b3, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#1a515c84, [ImportsContextCustomizer#672ec1ca key = [org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#51dd20fd, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#1a85aac8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#e2f4006e, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#9eb94ec], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> false]], class annotated with #DirtiesContext [false] with mode [null].
13:19:28.784 [Test worker] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.6.RELEASE)
2020-04-27 13:19:29.222 INFO 13608 --- [ Test worker] c.m.jokenpo.JokenpoApplicationTests : Starting JokenpoApplicationTests on SPANOT149 with PID 13608 (started by Cast in C:\WSs\KotlinGradleIntelliJ\jokenpo)
2020-04-27 13:19:29.222 INFO 13608 --- [ Test worker] c.m.jokenpo.JokenpoApplicationTests : No active profile set, falling back to default profiles: default
2020-04-27 13:19:30.008 INFO 13608 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-04-27 13:19:30.070 INFO 13608 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 64ms. Found 1 JPA repository interfaces.
2020-04-27 13:19:31.402 INFO 13608 --- [ Test worker] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
2020-04-27 13:19:31.424 INFO 13608 --- [ Test worker] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-04-27 13:19:31.424 INFO 13608 --- [ Test worker] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.33]
2020-04-27 13:19:31.595 INFO 13608 --- [ Test worker] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-04-27 13:19:31.595 INFO 13608 --- [ Test worker] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2343 ms
2020-04-27 13:19:31.675 INFO 13608 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-04-27 13:19:31.916 INFO 13608 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-04-27 13:19:31.916 INFO 13608 --- [ Test worker] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2020-04-27 13:19:32.218 INFO 13608 --- [ Test worker] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-04-27 13:19:32.301 INFO 13608 --- [ Test worker] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-04-27 13:19:32.382 INFO 13608 --- [ Test worker] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-04-27 13:19:32.533 INFO 13608 --- [ Test worker] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-04-27 13:19:33.002 INFO 13608 --- [ Test worker] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-04-27 13:19:33.018 INFO 13608 --- [ Test worker] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default
2020-04-27 13:19:33.202 WARN 13608 --- [ Test worker] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-04-27 13:19:33.487 INFO 13608 --- [ Test worker] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:33.836 INFO 13608 --- [ Test worker] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring TestDispatcherServlet ''
2020-04-27 13:19:33.836 INFO 13608 --- [ Test worker] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2020-04-27 13:19:33.851 INFO 13608 --- [ Test worker] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 15 ms
2020-04-27 13:19:33.904 INFO 13608 --- [ Test worker] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 56309 (http) with context path ''
2020-04-27 13:19:33.904 INFO 13608 --- [ Test worker] c.m.jokenpo.JokenpoApplicationTests : Started JokenpoApplicationTests in 5.107 seconds (JVM running for 7.245)
UserServiceTest STANDARD_OUT
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.mycomp.jokenpo.UserServiceTest], using SpringBootContextLoader
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] o.s.t.c.support.AbstractContextLoader : Could not detect default resource locations for test class [com.mycomp.jokenpo.UserServiceTest]: no resource found for suffixes {-context.xml, Context.groovy}.
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.mycomp.jokenpo.UserServiceTest]: UserServiceTest does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Found #SpringBootConfiguration com.mycomp.jokenpo.JokenpoApplication for test class com.mycomp.jokenpo.UserServiceTest
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
2020-04-27 13:19:34.605 INFO 13608 --- [ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#2401a061, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#7ef022b4, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#5970e47d, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#3a26795d, org.springframework.test.context.support.DirtiesContextTestExecutionListener#130dd4d0, org.springframework.test.context.transaction.TransactionalTestExecutionListener#6c97b187, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#321ae364, org.springframework.test.context.event.EventPublishingTestExecutionListener#3bff88eb, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#46296010, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#17e3eadb, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#72872a80, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#35784ceb, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#38dc83b4]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.6.RELEASE)
2020-04-27 13:19:34.653 INFO 13608 --- [ Test worker] com.mycomp.jokenpo.UserServiceTest : Starting UserServiceTest on SPANOT149 with PID 13608 (started by Cast in C:\WSs\KotlinGradleIntelliJ\jokenpo)
2020-04-27 13:19:34.653 INFO 13608 --- [ Test worker] com.mycomp.jokenpo.UserServiceTest : No active profile set, falling back to default profiles: default
2020-04-27 13:19:34.858 INFO 13608 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-04-27 13:19:34.858 INFO 13608 --- [ Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 13ms. Found 1 JPA repository interfaces.
2020-04-27 13:19:35.005 INFO 13608 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Starting...
2020-04-27 13:19:35.005 INFO 13608 --- [ Test worker] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Start completed.
2020-04-27 13:19:35.037 INFO 13608 --- [ Test worker] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-04-27 13:19:35.037 INFO 13608 --- [ Test worker] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-04-27 13:19:35.081 INFO 13608 --- [ Test worker] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-04-27 13:19:35.081 INFO 13608 --- [ Test worker] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-04-27 13:19:35.378 WARN 13608 --- [ Test worker] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-04-27 13:19:35.500 INFO 13608 --- [ Test worker] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:35.679 INFO 13608 --- [ Test worker] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2020-04-27 13:19:35.738 INFO 13608 --- [ Test worker] com.mycomp.jokenpo.UserServiceTest : Started UserServiceTest in 1.11 seconds (JVM running for 9.072)
2020-04-27 13:19:35.754 INFO 13608 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:35.755 INFO 13608 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:35.755 INFO 13608 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-04-27 13:19:35.756 INFO 13608 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-04-27 13:19:35.756 INFO 13608 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-04-27 13:19:35.756 INFO 13608 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-04-27 13:19:35.759 INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown initiated...
2020-04-27 13:19:35.759 INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-04-27 13:19:35.765 INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2020-04-27 13:19:35.765 INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Shutdown completed.
BUILD SUCCESSFUL in 14s
4 actionable tasks: 1 executed, 3 up-to-date
C:\WSs\KotlinGradleIntelliJ\jokenpo>
build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.2.6.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
kotlin("jvm") version "1.3.71"
kotlin("plugin.spring") version "1.3.71"
kotlin("plugin.jpa") version "1.3.71"
}
group = "com.mycomp"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8
val developmentOnly by configurations.creating
configurations {
runtimeClasspath {
extendsFrom(developmentOnly)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("com.h2database:h2")
//runtimeOnly("org.hsqldb:hsqldb")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
testImplementation ("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<Test> {
this.testLogging {
this.showStandardStreams = true
}
}
Test file
package com.mycomp.jokenpo
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.mycomp.jokenpo.enums.PlayType
import com.mycomp.jokenpo.model.User
import com.mycomp.jokenpo.respository.UserRepository
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
import org.springframework.web.util.NestedServletException
#AutoConfigureMockMvc
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ExtendWith(SpringExtension::class, MockitoExtension::class)
class JokenpoApplicationTests {
#Autowired
private lateinit var mockMvc: MockMvc
#MockBean
lateinit var respository: UserRepository
#BeforeEach
fun setup() {
whenever(respository.save(User(1, "Test", PlayType.LAGARTO))).thenAnswer {
it.arguments.first()
}
}
#Test
fun `Test createUser in the happy path scenario`() {
val user = User(1, "Test", PlayType.LAGARTO)
mockMvc.post("/users/") {
contentType = MediaType.APPLICATION_JSON
content = jacksonObjectMapper().writeValueAsString(user)
accept = MediaType.APPLICATION_JSON
}.andExpect {
status { isOk }
content { contentType(MediaType.APPLICATION_JSON) }
content { json("""{"id":1,"name":"Test"}""") }
}
//verify(respository, times(1)).save(user)
}
#Test
fun `Test negative scenario of createUser`() {
val user = User(2, "Test", PlayType.LAGARTO)
assertThrows<NestedServletException> {
mockMvc.post("/users/") {
contentType = MediaType.APPLICATION_JSON
content = jacksonObjectMapper().writeValueAsString(user)
accept = MediaType.APPLICATION_JSON
}
}
verify(respository, times(1)).save(user)
}
#Test
fun findUser() {
mockMvc.get("/users?id=99")
.andExpect {
status { isOk }
}
verify(respository, times(1)).findAll()
}
}
PS.: I don't see any change in output if I try "gradle clean test" or point the file with "gradle test --tests JokenpoApplicationTests"
I am confused if my tests are execcuted but I miss some Gradle configutarion to shw the result or even worst my tests aren't executed at all and I lost some basic concept because IntelliJ adds this automatically and "hide" from my eyes
When using the Gradle rich console, test execution is reported in the dynamic part of the Gradle output. This means that once test finishes, that output is gone.
By doing
this.testLogging {
this.showStandardStreams = true
}
you only redirect the test outputs to the console.
Instead, have a look at the TestLoggingContainer documentation and consider logging tests passing and failed with something like:
testLogging {
events "passed", "failed"
}

spring batch ItemWriter creating output twice

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.

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 taking long time to start

I have a spring boot application where it listens to a RabbitMQ queue.
The problem is when i run my application it hangs at particular step at
hibernate and it takes around 10 minutes to further continue.
Below is where it hangs
INFO [] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
INFO [] org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 3338 ms
INFO [] org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService 'metricsExecutor'
INFO [] org.springframework.boot.context.embedded.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'metricFilter' to: [/*]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'webRequestLoggingFilter' to: [/*]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'applicationContextIdFilter' to: [/*]
[main] INFO [] org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default'
[main] INFO [] org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [
name: default
...]
[main] INFO [] org.hibernate.Version - HHH000412: Hibernate Core {4.3.7.Final}
[main] INFO [] org.hibernate.cfg.Environment - HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.format_sql=true, hibernate.ejb.naming_strategy=org.hibernate.cfg.DefaultNamingStrategy}
[main] INFO [] org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist
[main] INFO [] org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Below is the timing info
2015-07-08 09:31:16,714 [main] INFO [] org.hibernate.Version - HHH000412: Hibernate Core {4.3.7.Final}
2015-07-08 09:31:16,717 [main] INFO [] org.hibernate.cfg.Environment - HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.format_sql=true, hibernate.ejb.naming_strategy=org.hibernate.cfg.DefaultNamingStrategy}
2015-07-08 09:31:16,717 [main] INFO [] org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist
2015-07-08 09:31:16,895 [main] INFO [] org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
In the above line it hangs for 8 min, and then it generates the below log waiting for any message.
15-07-14 15:36:22,917 [main] INFO [] com.test.myApp.reporting.service.Application
- Starting Application on hyd-rupakular-m.local with PID 654 (/Users/myUser/code/myRepo/target/classes started by rupakulr in /Users/myuser/myRepo/xyzabc)
2015-07-14 15:36:22,966 [main] INFO [] org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5fa0d903: startup date [Tue Jul 14 15:36:22 IST 2015]; root of context hierarchy
2015-07-14 15:36:24,023 [main] INFO [] org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [spring-integration-context.xml]
2015-07-14 15:36:24,332 [main] INFO [] org.springframework.beans.factory.config.PropertiesFactoryBean - Loading properties file from URL [jar:file:/Users/rupakulr/.m2/repository/org/springframework/integration/spring-integration-core/4.1.2.RELEASE/spring-integration-core-4.1.2.RELEASE.jar!/META-INF/spring.integration.default.properties]
2015-07-14 15:45:09,646 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/env],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,646 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/metrics/{name:.*}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2015-07-14 15:45:09,646 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/metrics],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,647 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/mappings],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,647 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/trace],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,647 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/shutdown],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.ShutdownMvcEndpoint.invoke()
2015-07-14 15:45:09,647 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/beans],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,700 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
2015-07-14 15:45:09,708 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Bean with name 'org.springframework.integration.channel.interceptor.WireTap#0' has been autodetected for JMX exposure
2015-07-14 15:45:09,708 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Bean with name 'org.springframework.integration.channel.interceptor.WireTap#1' has been autodetected for JMX exposure
2015-07-14 15:45:09,709 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Bean with name 'org.springframework.integration.config.RouterFactoryBean#0' has been autodetected for JMX exposure
2015-07-14 15:45:09,712 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Located managed bean 'org.springframework.integration.channel.interceptor.WireTap#0': registering with JMX server as MBean [org.springframework.integration.channel.interceptor:name=org.springframework.integration.channel.interceptor.WireTap#0,type=WireTap]
2015-07-14 15:45:09,726 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Located managed bean 'org.springframework.integration.channel.interceptor.WireTap#1': registering with JMX server as MBean [org.springframework.integration.channel.interceptor:name=org.springframework.integration.channel.interceptor.WireTap#1,type=WireTap]
2015-07-14 15:45:09,730 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Located managed bean 'org.springframework.integration.config.RouterFactoryBean#0': registering with JMX server as MBean [org.springframework.integration.router:name=org.springframework.integration.config.RouterFactoryBean#0,type=HeaderValueRouter]
2015-07-14 15:45:09,745 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Registering beans for JMX exposure on startup
2015-07-14 15:45:09,749 [main] INFO [] org.springframework.context.support.DefaultLifecycleProcessor - Starting beans in phase -2147483648
2015-07-14 15:45:09,750 [main] INFO [] org.springframework.context.support.DefaultLifecycleProcessor - Starting beans in phase 0
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {router} as a subscriber to the 'reporting-dealer-compliance-dealer-list-channel' channel
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.reporting-dealer-compliance-dealer-list-channel' has 1 subscriber(s).
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#0
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {object-to-json-transformer} as a subscriber to the 'reporting-dealer-compliance-dealer-compliance-json-channel' channel
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.reporting-dealer-compliance-dealer-compliance-json-channel' has 1 subscriber(s).
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#1
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {logging-channel-adapter:logging-channel.adapter} as a subscriber to the 'logging-channel' channel
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.logging-channel' has 1 subscriber(s).
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started logging-channel.adapter
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {stream:outbound-channel-adapter(character):std-out-channel.adapter} as a subscriber to the 'std-out-channel' channel
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.std-out-channel' has 1 subscriber(s).
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started std-out-channel.adapter
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.amqp.inbound.AmqpInboundGateway - started org.springframework.integration.amqp.inbound.AmqpInboundGateway#0
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {amqp:outbound-channel-adapter:invalidMessageChannelAdapter} as a subscriber to the 'invalid-message-channel' channel
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.invalid-message-channel' has 2 subscriber(s).
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started invalidMessageChannelAdapter
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {service-activator} as a subscriber to the 'failed-channel' channel
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.failed-channel' has 1 subscriber(s).
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#2
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {amqp:outbound-channel-adapter:failedMessageChannelAdapter} as a subscriber to the 'failed-channel' channel
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.failed-channel' has 2 subscriber(s).
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started failedMessageChannelAdapter
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.handler.MessageHandlerChain - started org.springframework.integration.handler.MessageHandlerChain#0
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {chain} as a subscriber to the 'reporting-dealer-compliance-inbound-channel' channel
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.reporting-dealer-compliance-inbound-channel' has 1 subscriber(s).
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#3
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.handler.MessageHandlerChain - started org.springframework.integration.handler.MessageHandlerChain#1
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {chain} as a subscriber to the 'prepare-csv' channel
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.prepare-csv' has 1 subscriber(s).
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#4
2015-07-14 15:45:10,971 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint]
2015-07-14 15:45:10,979 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint]
2015-07-14 15:45:10,986 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint]
2015-07-14 15:45:10,992 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint]
2015-07-14 15:45:10,997 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint]
2015-07-14 15:45:11,003 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint]
2015-07-14 15:45:11,009 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint]
2015-07-14 15:45:11,014 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint]
2015-07-14 15:45:11,020 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'autoConfigurationAuditEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationAuditEndpoint]
2015-07-14 15:45:11,026 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'shutdownEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=shutdownEndpoint]
2015-07-14 15:45:11,032 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint]
2015-07-14 15:45:11,037 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2015-07-14 15:45:11,037 [main] INFO [] org.springframework.integration.channel.PublishSubscribeChannel - Channel 'application:8204.errorChannel' has 1 subscriber(s).
2015-07-14 15:45:11,037 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started _org.springframework.integration.errorLogger
2015-07-14 15:45:11,037 [main] INFO [] org.springframework.context.support.DefaultLifecycleProcessor - Starting beans in phase 2147483647
2015-07-14 15:45:11,089 [main] INFO [] org.apache.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8204"]
2015-07-14 15:45:11,095 [main] INFO [] org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8204"]
2015-07-14 15:45:11,100 [main] INFO [] org.apache.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read
2015-07-14 15:45:11,112 [main] INFO [] org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8204 (http)
2015-07-14 15:45:11,115 [main] INFO [] com.test.myApp.reporting.service.Application - Started Application in 528.444 seconds (JVM running for 529.101)
we are experiencing a lot of problem when developing our app, every time we make some changes we have to wait 8 min to test our changes.
In case you are running your application on Linux, try to add this property to the java commandline:
-Djava.security.egd=file:/dev/./urandom
E.g.:
/usr/bin/java -Xmx75m -Djava.security.egd=file:/dev/./urandom -jar app.jar
I had a similar problem, although it did not take 8 minutes but only around 3 to start the application, and this solved it for me.
I think I faced with the similar issue. In my case time to start was proportional to the database size. And the entire problem was that hibernate (we use hibernate-core-5.0.2-Final) loads full metadata from DB just for obtaining Dialect value.
We now use following property to disable:
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
But make sure you specify 'spring.jpa.database-platform' value correct.
Here is related part of JdbcEnvironmentInitiator.java file:
#Override
public JdbcEnvironment initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
final DialectFactory dialectFactory = registry.getService( DialectFactory.class );
// 'hibernate.temp.use_jdbc_metadata_defaults' is a temporary magic value.
// The need for it is intended to be alleviated with future development, thus it is
// not defined as an Environment constant...
//
// it is used to control whether we should consult the JDBC metadata to determine
// certain Settings default values; it is useful to *not* do this when the database
// may not be available (mainly in tools usage).
boolean useJdbcMetadata = ConfigurationHelper.getBoolean(
"hibernate.temp.use_jdbc_metadata_defaults",
configurationValues,
true
);
if ( useJdbcMetadata ) {
final JdbcConnectionAccess jdbcConnectionAccess = buildJdbcConnectionAccess( configurationValues, registry );
try {
final Connection connection = jdbcConnectionAccess.obtainConnection();
try {
final DatabaseMetaData dbmd = connection.getMetaData();
if ( log.isDebugEnabled() ) {
log.debugf(
"Database ->\n"
+ " name : %s\n"
+ " version : %s\n"
+ " major : %s\n"
+ " minor : %s",
dbmd.getDatabaseProductName(),
dbmd.getDatabaseProductVersion(),
dbmd.getDatabaseMajorVersion(),
dbmd.getDatabaseMinorVersion()
);
log.debugf(
"Driver ->\n"
+ " name : %s\n"
+ " version : %s\n"
+ " major : %s\n"
+ " minor : %s",
dbmd.getDriverName(),
dbmd.getDriverVersion(),
dbmd.getDriverMajorVersion(),
dbmd.getDriverMinorVersion()
);
log.debugf( "JDBC version : %s.%s", dbmd.getJDBCMajorVersion(), dbmd.getJDBCMinorVersion() );
}
Dialect dialect = dialectFactory.buildDialect(
configurationValues,
new DialectResolutionInfoSource() {
#Override
public DialectResolutionInfo getDialectResolutionInfo() {
try {
return new DatabaseMetaDataDialectResolutionInfoAdapter( connection.getMetaData() );
}
catch ( SQLException sqlException ) {
throw new HibernateException(
"Unable to access java.sql.DatabaseMetaData to determine appropriate Dialect to use",
sqlException
);
}
}
}
);
return new JdbcEnvironmentImpl(
registry,
dialect,
dbmd
);
}
catch (SQLException e) {
log.unableToObtainConnectionMetadata( e.getMessage() );
}
finally {
try {
jdbcConnectionAccess.releaseConnection( connection );
}
catch (SQLException ignore) {
}
}
}
catch (Exception e) {
log.unableToObtainConnectionToQueryMetadata( e.getMessage() );
}
}
// if we get here, either we were asked to not use JDBC metadata or accessing the JDBC metadata failed.
return new JdbcEnvironmentImpl( registry, dialectFactory.buildDialect( configurationValues, null ) );
}

Resources