I have a Gradle project which uses Spring core and Spring JDBC and it runs succesfully if I do a Gradle run. The project does not run when I convert that into a fat jar.
I suspect that Spring configuration is not getting loaded before the main program is run. I use Gradle to build the fat jar which looks good. I have added pictures of the error and the fat jar. This is the error log.
C:\CGIADM\Utils\advhealthcheck>java -jar build\libs\advhealthcheck.jar
2019-09-13 16:38:55,625 main DEBUG null null initializing configuration XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml]
2019-09-13 16:38:55,625 main DEBUG Installed 1 script engine
2019-09-13 16:38:55,828 main DEBUG Oracle Nashorn version: 1.8.0_151, language: ECMAScript, threading: Not Thread Safe, compile: true, names: [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript], factory class: jdk.nashorn.api.scripting.NashornScriptEngineFactory
2019-09-13 16:38:55,828 main DEBUG PluginManager 'Core' found 117 plugins
2019-09-13 16:38:55,828 main DEBUG PluginManager 'Level' found 0 plugins
2019-09-13 16:38:55,828 main DEBUG Building Plugin[name=property, class=org.apache.logging.log4j.core.config.Property].
2019-09-13 16:38:55,844 main DEBUG PluginManager 'TypeConverter' found 26 plugins
2019-09-13 16:38:55,844 main DEBUG createProperty(name="pattern", value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n")
2019-09-13 16:38:55,844 main DEBUG Building Plugin[name=property, class=org.apache.logging.log4j.core.config.Property].
2019-09-13 16:38:55,844 main DEBUG createProperty(name="basePath", value="./log")
2019-09-13 16:38:55,844 main DEBUG Building Plugin[name=properties, class=org.apache.logging.log4j.core.config.PropertiesPlugin].
2019-09-13 16:38:55,844 main DEBUG configureSubstitutor(={pattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n, basePath=./log}, Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml))
2019-09-13 16:38:55,844 main DEBUG PluginManager 'Lookup' found 13 plugins
2019-09-13 16:38:55,844 main DEBUG Building Plugin[name=Route, class=org.apache.logging.log4j.core.appender.routing.Route].
2019-09-13 16:38:55,860 main DEBUG createRoute(ref="null", key="${ctx:healthcheck}", Node=Route)
2019-09-13 16:38:55,860 main DEBUG Building Plugin[name=Route, class=org.apache.logging.log4j.core.appender.routing.Route].
2019-09-13 16:38:55,860 main DEBUG createRoute(ref="null", key="null", Node=Route)
2019-09-13 16:38:55,860 main DEBUG Building Plugin[name=Routes, class=org.apache.logging.log4j.core.appender.routing.Routes].
2019-09-13 16:38:55,860 main DEBUG Routes$Builder(Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), pattern="${ctx:healthcheck}", Script=null, ={Route(type=dynamic - type=Route key='${ctx:healthcheck}'), Route(type=dynamic - type=Route default)})
2019-09-13 16:38:55,860 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.routing.RoutingAppender].
2019-09-13 16:38:55,875 main DEBUG RoutingAppender$Builder(Script=null, Routes({Route(type=dynamic - type=Route key='${ctx:healthcheck}'),Route(type=dynamic - type=Route default)}), RewritePolicy=null, PurgePolicy=null, ignoreExceptions="null", Layout=null, name="Routing", Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), Filter=null, ={})
2019-09-13 16:38:55,875 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2019-09-13 16:38:55,875 main DEBUG PatternLayout$Builder(pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n", PatternSelector=null, Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2019-09-13 16:38:55,875 main DEBUG PluginManager 'Converter' found 44 plugins
2019-09-13 16:38:55,875 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2019-09-13 16:38:55,891 main DEBUG ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n), name="console", Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), Filter=null, ={})
2019-09-13 16:38:55,891 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2019-09-13 16:38:55,891 main DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2019-09-13 16:38:55,891 main DEBUG createAppenders(={Routing, console})
2019-09-13 16:38:55,891 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2019-09-13 16:38:55,891 main DEBUG createAppenderRef(ref="Routing", level="null", Filter=null)
2019-09-13 16:38:55,891 main DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2019-09-13 16:38:55,891 main DEBUG createLogger(additivity="null", level="INFO", includeLocation="null", ={Routing}, ={}, Configuration(jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml), Filter=null)
2019-09-13 16:38:55,891 main DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2019-09-13 16:38:55,891 main DEBUG createLoggers(={root})
2019-09-13 16:38:55,891 main DEBUG Configuration XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml] initialized
2019-09-13 16:38:55,891 main DEBUG Starting configuration XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml]
2019-09-13 16:38:55,891 main DEBUG Started configuration XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml] OK.
2019-09-13 16:38:55,891 main DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2019-09-13 16:38:55,891 main DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
2019-09-13 16:38:55,907 main DEBUG Appender DefaultConsole-1 stopped with status true
2019-09-13 16:38:55,907 main DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration#48533e64 OK
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=StatusLogger
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=ContextSelector
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=Loggers,name=
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=Appenders,name=Routing
2019-09-13 16:38:55,938 main DEBUG Registering MBean org.apache.logging.log4j2:type=5c647e05,component=Appenders,name=console
2019-09-13 16:38:55,938 main DEBUG org.apache.logging.log4j.core.util.SystemClock does not support precise timestamps.
2019-09-13 16:38:55,938 main DEBUG Reconfiguration complete for context[name=5c647e05] at URI jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml (org.apache.logging.log4j.core.LoggerContext#74235045) with optional ClassLoader: null
2019-09-13 16:38:55,938 main DEBUG Shutdown hook enabled. Registering a new one.
2019-09-13 16:38:55,953 main DEBUG LoggerContext[name=5c647e05, org.apache.logging.log4j.core.LoggerContext#74235045] started OK.
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.IllegalStateException: Cannot load configuration class: adv.healthcheck.conn.SpringJdbcConfig
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:404)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:249)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:283)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:127)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at adv.tasks.AdvHealthCheckTaskProcessor.addTaskToList(AdvHealthCheckTaskProcessor.java:71)
at adv.tasks.AdvHealthCheckTaskProcessor.runMainHealthCheckProcessor(AdvHealthCheckTaskProcessor.java:36)
at adv.tasks.AdvHealthCheckTaskProcessor.main(AdvHealthCheckTaskProcessor.java:31)
Caused by: java.lang.IllegalStateException: Unable to load cache item
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:79)
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:337)
at org.springframework.context.annotation.ConfigurationClassEnhancer.createClass(ConfigurationClassEnhancer.java:138)
at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:110)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:394)
... 9 more
Caused by: java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:467)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
... 17 more
Caused by: java.util.NoSuchElementException: get() on Left
at io.vavr.control.Either$Left.get(Either.java:935)
at adv.healthcheck.conn.SpringJdbcConfig.<clinit>(SpringJdbcConfig.java:20)
... 27 more
2019-09-13 16:38:56,203 pool-1-thread-1 DEBUG Stopping LoggerContext[name=5c647e05, org.apache.logging.log4j.core.LoggerContext#74235045]
2019-09-13 16:38:56,203 pool-1-thread-1 DEBUG Stopping LoggerContext[name=5c647e05, org.apache.logging.log4j.core.LoggerContext#74235045]...
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false, all resources released: true
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Appender console stopped with status true
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Stopped XmlConfiguration[location=jar:file:/C:/CGIADM/Utils/advhealthcheck/build/libs/advhealthcheck.jar!/log4j2.xml] OK
2019-09-13 16:38:56,219 pool-1-thread-1 DEBUG Stopped LoggerContext[name=5c647e05, org.apache.logging.log4j.core.LoggerContext#74235045] with status true
import static adv.util.AdvHealthCheckFileUtils.loadAppConfigFile;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
#Configuration
public class SpringJdbcConfig {
private static String DRIVER_CLASS_NAME = "driverClassName";
private static String JDBC_URL = "jdbcurl";
private static String SCHEMA_USERNAME = "userName";
private static String SCHEMA_PASSWORD = "password";
static Properties props;
static {
props = loadAppConfigFile().get();
}
#Bean
public DataSource dataSource() {
return myJdbcDataSource();
}
// #Bean
public DataSource myJdbcDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(props.getProperty(DRIVER_CLASS_NAME));
dataSource.setUrl(props.getProperty(JDBC_URL));
dataSource.setUsername(props.getProperty(SCHEMA_USERNAME));
dataSource.setPassword(props.getProperty(SCHEMA_PASSWORD));
return dataSource;
}
}
Related
Creating a simple spring boot project using kotlin+Gradle and I get the following error from AWS
ATEST]7eaf7391bd074416bb2acc17a521a803, AWS_LAMBDA_INITIALIZATION_TYPE=on-demand, AWS_XRAY_DAEMON_ADDRESS=169.254.79.2:2000, _AWS_XRAY_DAEMON_PORT=2000, AWS_XRAY_CONTEXT_MISSING=LOG_ERROR, AWS_LAMBDA_FUNCTION_VERSION=$LATEST, AWS_ACCESS_KEY=ASIAU7C4QO4VEP4KLVH2, AWS_LAMBDA_FUNCTION_NAME=swaves-beach-rate}
00:14:04.221 [main] INFO org.springframework.cloud.function.adapter.aws.CustomRuntimeInitializer - AWS Handler: org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler
00:14:04.321 [main] INFO lambdainternal.AWSLambda - Starting AWSLambda using Java 11.0.11 on 169.254.24.133 with PID 8 (/var/runtime/lib/aws-lambda-java-runtime-0.2.0.jar started by sbx_user1051 in /var/task)
00:14:04.321 [main] DEBUG lambdainternal.AWSLambda - Running with Spring Boot, Spring
00:14:04.321 [main] INFO lambdainternal.AWSLambda - No active profile set, falling back to default profiles: default
00:14:04.323 [main] DEBUG org.springframework.boot.SpringApplication - Loading source class com.aio.swaves.SwavesApplication
00:14:04.767 [main] DEBUG org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext#204f30ec
00:14:04.807 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
00:14:07.024 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
00:14:07.028 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
00:14:07.039 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
00:14:07.059 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
00:14:07.083 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'swavesApplication'
00:14:07.099 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'greet'
00:14:07.139 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.AutoConfigurationPackages'
00:14:07.140 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.cloud.function.adapter.aws.CustomRuntimeEventLoop'
00:14:07.205 [main] INFO lambdainternal.AWSLambda - Started AWSLambda in 3.652 seconds (JVM running for 4.394)
00:14:08.210 [main] DEBUG reactor.util.Loggers - Using Slf4j logging framework
No function defined: java.lang.IllegalStateException
java.lang.IllegalStateException: No function defined
at org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.apply(AbstractSpringFunctionAdapterInitializer.java:189)
at org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler.handleRequest(SpringBootStreamHandler.java:55)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
END RequestId: 7ea16b3f-47d5-4763-b9fe-f97d940cf55c
REPORT RequestId: 7ea16b3f-47d5-4763-b9fe-f97d940cf55c Duration: 5006.33 ms Billed Duration: 5007 ms Memory Size: 1024 MB Max Memory Used: 166 MB Init Duration: 546.69 ms
build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.github.jengelman.gradle.plugins.shadow.transformers.*
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
id("org.springframework.boot") version "2.5.4"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
id("com.github.johnrengelman.shadow") version "7.0.0"
kotlin("jvm") version "1.5.21"
kotlin("plugin.spring") version "1.5.21"
}
group = "com.aio"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
val springCloudVersion = "2020.0.3"
val awsLambdaEventsVersion = "3.10.0"
val awsLambdaCoreVersion = "1.2.1"
dependencies {
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("org.springframework.cloud:spring-cloud-function-web")
implementation("org.springframework.cloud:spring-cloud-function-adapter-aws")
implementation("org.jsoup:jsoup:1.14.2")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
runtimeOnly("com.amazonaws:aws-lambda-java-core:${awsLambdaCoreVersion}")
runtimeOnly("com.amazonaws:aws-lambda-java-events:${awsLambdaEventsVersion}")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(module = "junit")
exclude(module = "mockito-core")
}
testImplementation("io.projectreactor:reactor-test")
testImplementation("org.junit.jupiter:junit-jupiter-api")
testImplementation("com.ninja-squad:springmockk:3.0.1")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
}
dependencyManagement {
imports {
mavenBom("org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}")
}
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.assemble{
dependsOn("shadowJar")
}
tasks.withType<Jar> {
manifest {
attributes["Start-Class"] = "com.aio.swaves.SwavesApplication"
}
}
tasks.withType<ShadowJar> {
archiveClassifier.set("aws")
archiveFileName.set("swaves.jar")
dependencies {
exclude(
dependency("org.springframework.cloud:spring-cloud-function-web:3.1.3"))
}
// Required for Spring
mergeServiceFiles()
append("META-INF/spring.handlers")
append ("META-INF/spring.schemas")
append("META-INF/spring.tooling")
transform(PropertiesFileTransformer::class.java) {
val paths = arrayOf("META-INF/spring.factories")
val mergeStrategy = "append"
}
}
application.yml
spring:
cloud:
function:
definition: greet
profiles:
active: production
SwavesApplication.kt
package com.aio.swaves
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
#SpringBootApplication
class SwavesApplication {
#Bean
fun greet(): (String) -> String {
return { "Hello Kotlin" }
}
}
fun main(args: Array<String>) {
runApplication<SwavesApplication>(*args)
}
Notes
Notice that the error says that there is not active profile, so it will select the default, despite that the application.yml is setting an active profile to production.
Also notice that the Bean greet is created, which means that the start-class attribute is correctly configured. I am a bit lost in what is missed, I have make it work using java but not Kotlin any suggestion?
Thanks to Oleg Zhurakousky's answer, I took my time to create samples project and document it at github. In the samples, you will find even how I push the code to AWS Lambda.
The error is that I was using the deprecated SpringBootStreamHandler instead the new FunctionInvoker.
currently I have a project with Spring MVC which already interact with Database(MariaDB) and I would like to try the spring-session-jdbc. I found the documentation in this spring-session , I do what the documentation is says but the app don't start when I deploy it in the Tomcat. And the log in the Tomcat is not very helpful. Here is my code:
#Configuration
#PropertySource("classpath:application.properties")
#EnableTransactionManagement
#EnableJdbcHttpSession
#ComponentScans(value = {#ComponentScan("com.havistudio.web.testapp.dao"), #ComponentScan("com.havistudio.web.testapp.service")})
public class AppConfig {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.havistudio.web.testapp.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setJdbcUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
dataSource.setConnectionTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.connection-timeout")));
dataSource.setMinimumIdle(Integer.parseInt(environment.getRequiredProperty("spring.datasource.hikari.minimum-idle")));
dataSource.setMaximumPoolSize(Integer.parseInt(environment.getRequiredProperty("spring.datasource.hikari.maximum-pool-size")));
dataSource.setIdleTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.idle-timeout")));
dataSource.setMaxLifetime(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.max-lifetime")));
dataSource.setAutoCommit(Boolean.parseBoolean(environment.getRequiredProperty("spring.datasource.hikari.auto-commit")));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public JavaMailSender getMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
//Using gmail
mailSender.setHost("mail.test.com");
mailSender.setPort(587);
mailSender.setUsername("info#test.com");
mailSender.setPassword("dsffsdfsdfsd");
Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.smtp.auth", "true");
javaMailProperties.put("mail.smtp.starttls.enable", "true");
javaMailProperties.put("mail.smtp.ssl.trust", "mail.test.com");
//javaMailProperties.put("mail.debug", "true");//Prints out everything on screen
mailSender.setJavaMailProperties(javaMailProperties);
return mailSender;
}
}
My initializer:
public class MyInitializer extends AbstractHttpSessionApplicationInitializer {
public MyInitializer() {
super(AppConfig.class);
}
}
My application.properties
spring.session.store-type=jdbc
pom.xml
<!-- Spring Session JDBC -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
<version>2.5.1</version>
</dependency>
My log:
21-Aug-2021 18:23:45.336 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.undeploy Undeploying context [/TzokerStatisticsApp]
21-Aug-2021 18:23:45.694 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp.war]
2021-08-21 18:23:50,242 localhost-startStop-3 DEBUG Apache Log4j Core 2.14.1 initializing configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml]
2021-08-21 18:23:50,246 localhost-startStop-3 DEBUG Installed 1 script engine
Warning: Nashorn engine is planned to be removed from a future JDK release
2021-08-21 18:23:50,252 localhost-startStop-3 DEBUG Oracle Nashorn version: 11.0.11, language: ECMAScript, threading: Not Thread Safe, compile: true, names: [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript], factory class: jdk.nashorn.api.scripting.NashornScriptEngineFactory
2021-08-21 18:23:50,253 localhost-startStop-3 DEBUG PluginManager 'Core' found 122 plugins
2021-08-21 18:23:50,253 localhost-startStop-3 DEBUG PluginManager 'Level' found 0 plugins
2021-08-21 18:23:50,257 localhost-startStop-3 DEBUG PluginManager 'Lookup' found 16 plugins
2021-08-21 18:23:50,260 localhost-startStop-3 DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2021-08-21 18:23:50,273 localhost-startStop-3 DEBUG PluginManager 'TypeConverter' found 26 plugins
2021-08-21 18:23:50,282 localhost-startStop-3 DEBUG PatternLayout$Builder(pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n", PatternSelector=null, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2021-08-21 18:23:50,283 localhost-startStop-3 DEBUG PluginManager 'Converter' found 44 plugins
2021-08-21 18:23:50,284 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2021-08-21 18:23:50,294 localhost-startStop-3 DEBUG ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n), name="LogToConsole", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null, ={})
2021-08-21 18:23:50,296 localhost-startStop-3 DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2021-08-21 18:23:50,296 localhost-startStop-3 DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2021-08-21 18:23:50,297 localhost-startStop-3 DEBUG PatternLayout$Builder(pattern="%d %p %c{1.} [%t] %m%n", PatternSelector=null, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2021-08-21 18:23:50,323 localhost-startStop-3 DEBUG Building Plugin[name=TimeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy].
2021-08-21 18:23:50,327 localhost-startStop-3 DEBUG TimeBasedTriggeringPolicy$Builder(interval="null", modulate="null", maxRandomDelay="null")
2021-08-21 18:23:50,327 localhost-startStop-3 DEBUG Building Plugin[name=SizeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.SizeBasedTriggeringPolicy].
2021-08-21 18:23:50,333 localhost-startStop-3 DEBUG createPolicy(size="1 MB")
2021-08-21 18:23:50,335 localhost-startStop-3 DEBUG Building Plugin[name=Policies, class=org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy].
2021-08-21 18:23:50,336 localhost-startStop-3 DEBUG createPolicy(={TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)})
2021-08-21 18:23:50,336 localhost-startStop-3 DEBUG Building Plugin[name=DefaultRolloverStrategy, class=org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy].
2021-08-21 18:23:50,339 localhost-startStop-3 DEBUG DefaultRolloverStrategy$Builder(max="10", min="null", fileIndex="null", compressionLevel="null", ={}, stopCustomActionsOnError="null", tempCompressedFilePattern="null", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml))
2021-08-21 18:23:50,341 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender].
2021-08-21 18:23:50,344 localhost-startStop-3 DEBUG RollingRandomAccessFileAppender$Builder(fileName="logs/TzokerStatisticsApp/app.log", filePattern="logs/TzokerStatisticsApp/${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz", append="null", Policies(CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)])), DefaultRolloverStrategy(DefaultRolloverStrategy(min=1, max=10, useMax=true)), advertise="null", advertiseURI="null", filePermissions="null", fileOwner="null", fileGroup="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d %p %c{1.} [%t] %m%n), name="LogToRollingRandomAccessFile", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null, ={})
2021-08-21 18:23:50,354 localhost-startStop-3 DEBUG Starting RollingRandomAccessFileManager logs/TzokerStatisticsApp/app.log
2021-08-21 18:23:50,357 localhost-startStop-3 DEBUG PluginManager 'FileConverter' found 2 plugins
2021-08-21 18:23:50,365 localhost-startStop-3 DEBUG Setting prev file time to 2021-08-16T19:38:00.766+0300
2021-08-21 18:23:50,365 localhost-startStop-3 DEBUG Initializing triggering policy CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)])
2021-08-21 18:23:50,366 localhost-startStop-3 DEBUG Initializing triggering policy TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false)
2021-08-21 18:23:50,367 localhost-startStop-3 DEBUG Initializing triggering policy SizeBasedTriggeringPolicy(size=1048576)
2021-08-21 18:23:50,367 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,368 localhost-startStop-3 DEBUG createAppenderRef(ref="LogToRollingRandomAccessFile", level="null", Filter=null)
2021-08-21 18:23:50,368 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.AsyncAppender].
2021-08-21 18:23:50,370 localhost-startStop-3 DEBUG AsyncAppender$Builder(={LogToRollingRandomAccessFile}, errorRef="null", blocking="null", shutdownTimeout="null", bufferSize="null", name="Async", includeLocation="null", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), ignoreExceptions="null", BlockingQueueFactory=null, Filter=null, ={})
2021-08-21 18:23:50,371 localhost-startStop-3 DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2021-08-21 18:23:50,372 localhost-startStop-3 DEBUG createAppenders(={LogToConsole, LogToRollingRandomAccessFile, Async})
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG createAppenderRef(ref="Async", level="null", Filter=null)
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG Building Plugin[name=logger, class=org.apache.logging.log4j.core.config.LoggerConfig].
2021-08-21 18:23:50,376 localhost-startStop-3 DEBUG createLogger(additivity="false", level="DEBUG", name="com.havistudio.web.testapp", includeLocation="null", ={Async}, ={}, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null)
2021-08-21 18:23:50,382 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,382 localhost-startStop-3 DEBUG createAppenderRef(ref="LogToConsole", level="null", Filter=null)
2021-08-21 18:23:50,383 localhost-startStop-3 DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2021-08-21 18:23:50,384 localhost-startStop-3 DEBUG createLogger(additivity="null", level="ERROR", includeLocation="null", ={LogToConsole}, ={}, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null)
2021-08-21 18:23:50,385 localhost-startStop-3 DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2021-08-21 18:23:50,386 localhost-startStop-3 DEBUG createLoggers(={com.havistudio.web.testapp.root})
2021-08-21 18:23:50,388 localhost-startStop-3 DEBUG Configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml] initialized
2021-08-21 18:23:50,388 localhost-startStop-3 DEBUG Starting configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml]
2021-08-21 18:23:50,395 localhost-startStop-3 DEBUG org.apache.logging.log4j.core.util.SystemClock supports precise timestamps.
2021-08-21 18:23:50,399 localhost-startStop-3 DEBUG Started configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml] OK.
2021-08-21 18:23:50,399 localhost-startStop-3 DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG OutputStream closed
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG Appender DefaultConsole-1 stopped with status true
2021-08-21 18:23:50,401 localhost-startStop-3 DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration#39d9ebd0 OK
2021-08-21 18:23:50,407 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b
2021-08-21 18:23:50,410 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=StatusLogger
2021-08-21 18:23:50,412 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=ContextSelector
2021-08-21 18:23:50,415 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Loggers,name=
2021-08-21 18:23:50,415 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Loggers,name=com.havistudio.web.testapp
2021-08-21 18:23:50,417 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Appenders,name=LogToRollingRandomAccessFile
2021-08-21 18:23:50,418 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Appenders,name=LogToConsole
2021-08-21 18:23:50,420 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=AsyncAppenders,name=Async
2021-08-21 18:23:50,421 localhost-startStop-3 DEBUG Reconfiguration complete for context[name=5a383f6b] at URI C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml (org.apache.logging.log4j.core.LoggerContext#73aa23c5) with optional ClassLoader: null
2021-08-21 18:23:50,423 localhost-startStop-3 DEBUG Shutdown hook enabled. Registering a new one.
2021-08-21 18:23:50,425 localhost-startStop-3 DEBUG LoggerContext[name=5a383f6b, org.apache.logging.log4j.core.LoggerContext#73aa23c5] started OK.
21-Aug-2021 18:23:50.606 INFO [localhost-startStop-3] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Starting...
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Start completed.
21-Aug-2021 18:23:51.592 SEVERE [localhost-startStop-3] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
21-Aug-2021 18:23:51.593 SEVERE [localhost-startStop-3] org.apache.catalina.core.StandardContext.startInternal Context [/TzokerStatisticsApp] startup failed due to previous errors
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Shutdown initiated...
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Shutdown completed.
21-Aug-2021 18:23:51.624 WARNING [localhost-startStop-3] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [TzokerStatisticsApp] registered the JDBC driver [org.mariadb.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
21-Aug-2021 18:23:51.624 WARNING [localhost-startStop-3] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [TzokerStatisticsApp] appears to have started a thread named [Log4j2-AsyncAppenderEventDispatcher-1-Async] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
java.base#11.0.11/jdk.internal.misc.Unsafe.park(Native Method)
java.base#11.0.11/java.util.concurrent.locks.LockSupport.park(LockSupport.java:194)
java.base#11.0.11/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2081)
java.base#11.0.11/java.util.concurrent.ArrayBlockingQueue.take(ArrayBlockingQueue.java:417)
org.apache.logging.log4j.core.appender.AsyncAppenderEventDispatcher.dispatchAll(AsyncAppenderEventDispatcher.java:70)
org.apache.logging.log4j.core.appender.AsyncAppenderEventDispatcher.run(AsyncAppenderEventDispatcher.java:62)
21-Aug-2021 18:23:51.627 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp.war] has finished in [5,933] ms
I am sure I am missing something here, but I don't know what is it.
Finally, I found what was wrong! I took a deeper look in the logs file and specifically in the localhost*.log file and I found this:
3 Spring WebApplicationInitializers detected on classpath
22-Aug-2021 11:15:52.337 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
22-Aug-2021 11:15:53.251 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:263)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4768)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5236)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:744)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:980)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1851)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
Then I modify my MyInitializer class to this:
public class MyInitializer extends AbstractHttpSessionApplicationInitializer {
}
And immediately it worked like a charm!
In my application, I'm using spring boot 2.0.3 and have slf4j with log4j2 configured for logging.
However, I'm not able to get the setup write the logs to the file. I tried many ways but could not make it work. I don't understand what I'm missing here :/
My pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>${spring.boot.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring.boot.version}</version>
</dependency>
My log4j2.properties file
status = debug
name= properties_configuration
# Give directory path where log files should get stored
property.basePath = /A/B/c-web
# ConsoleAppender will print logs on console
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.target = SYSTEM_OUT
appender.console.layout.type = PatternLayout
# Specify the pattern of the logs
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n
# RollingFileAppender will print logs in file which can be rotated based on time or size
appender.rolling.type = RollingFile
appender.rolling.name = fileLogger
appender.rolling.fileName= ${basePath}/c-web.log
appender.rolling.filePattern= ${basePath}/archive/c-web_%d{yyyyMMdd}.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n
appender.rolling.policies.type = Policies
# Rotate log file each day and keep 30 days worth
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.delete.type = Delete
appender.rolling.strategy.delete.basePath = ${basePath}/archive
appender.rolling.strategy.delete.maxDepth = 1
appender.rolling.strategy.delete.ifLastModified.type = IfLastModified
# Delete files older than 30 days
appender.rolling.strategy.delete.ifLastModified.age = 30d
# Mention package name here in place of example. Classes in this package or subpackages will use ConsoleAppender and RollingFileAppender for logging
logger.rolling.name = com.x
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = fileLogger
logger.rolling.appenderRef.console.ref = consoleLogger
# Configure root logger for logging error logs in classes which are in package other than above specified package
rootLogger.level = info
rootLogger.additivity = false
rootLogger.appenderRef.rolling.ref = fileLogger
rootLogger.appenderRef.console.ref = consoleLogger
Application log during bootup
2018-10-28 20:14:50,463 main DEBUG PluginManager 'Core' found 116 plugins
2018-10-28 20:14:50,463 main DEBUG PluginManager 'Level' found 0 plugins
2018-10-28 20:14:50,468 main DEBUG Building Plugin[name=property, class=org.apache.logging.log4j.core.config.Property].
2018-10-28 20:14:50,483 main DEBUG PluginManager 'TypeConverter' found 26 plugins
2018-10-28 20:14:50,493 main DEBUG createProperty(name="basePath", value="/A/B/c-web")
2018-10-28 20:14:50,493 main DEBUG Building Plugin[name=properties, class=org.apache.logging.log4j.core.config.PropertiesPlugin].
2018-10-28 20:14:50,498 main DEBUG configureSubstitutor(={basePath=/A/B/c-web}, Configuration(properties_configuration))
2018-10-28 20:14:50,499 main DEBUG PluginManager 'Lookup' found 13 plugins
2018-10-28 20:14:50,499 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2018-10-28 20:14:50,499 main DEBUG createAppenderRef(ref="consoleLogger", level="null", Filter=null)
2018-10-28 20:14:50,500 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2018-10-28 20:14:50,500 main DEBUG createAppenderRef(ref="fileLogger", level="null", Filter=null)
2018-10-28 20:14:50,500 main DEBUG Building Plugin[name=logger, class=org.apache.logging.log4j.core.config.LoggerConfig].
2018-10-28 20:14:50,504 main DEBUG createLogger(additivity="false", level="DEBUG", name="com.x", includeLocation="null", ={consoleLogger, fileLogger}, ={}, Configuration(properties_configuration), Filter=null)
2018-10-28 20:14:50,506 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2018-10-28 20:14:50,507 main DEBUG createAppenderRef(ref="consoleLogger", level="null", Filter=null)
2018-10-28 20:14:50,507 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2018-10-28 20:14:50,507 main DEBUG createAppenderRef(ref="fileLogger", level="null", Filter=null)
2018-10-28 20:14:50,508 main DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2018-10-28 20:14:50,509 main DEBUG createLogger(additivity="null", level="INFO", includeLocation="null", ={consoleLogger, fileLogger}, ={}, Configuration(properties_configuration), Filter=null)
2018-10-28 20:14:50,509 main DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2018-10-28 20:14:50,510 main DEBUG createLoggers(={com.x, root})
2018-10-28 20:14:50,510 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2018-10-28 20:14:50,515 main DEBUG PatternLayout$Builder(pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n", PatternSelector=null, Configuration(properties_configuration), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2018-10-28 20:14:50,515 main DEBUG PluginManager 'Converter' found 47 plugins
2018-10-28 20:14:50,528 main DEBUG Building Plugin[name=IfLastModified, class=org.apache.logging.log4j.core.appender.rolling.action.IfLastModified].
2018-10-28 20:14:50,529 main DEBUG createAgeCondition(age="P30D", ={})
2018-10-28 20:14:50,530 main DEBUG org.apache.logging.log4j.core.util.SystemClock does not support precise timestamps.
2018-10-28 20:14:50,531 main DEBUG Building Plugin[name=Delete, class=org.apache.logging.log4j.core.appender.rolling.action.DeleteAction].
2018-10-28 20:14:50,532 main DEBUG createDeleteAction(basePath="/A/B/c-web/archive", followLinks="false", maxDepth="1", testMode="false", PathSorter=null, ={IfLastModified(age=P30D)}, ScriptCondition=null, Configuration(properties_configuration))
2018-10-28 20:14:50,532 main DEBUG Building Plugin[name=DefaultRolloverStrategy, class=org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy].
2018-10-28 20:14:50,542 main DEBUG DefaultRolloverStrategy$Builder(max="null", min="null", fileIndex="null", compressionLevel="null", ={DeleteAction[basePath=/A/B/c-web/archive, options=[], maxDepth=1, conditions=[IfLastModified(age=P30D)]]}, stopCustomActionsOnError="null", tempCompressedFilePattern="null", Configuration(properties_configuration))
2018-10-28 20:14:50,542 main DEBUG Building Plugin[name=TimeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy].
2018-10-28 20:14:50,544 main DEBUG TimeBasedTriggeringPolicy$Builder(interval="1", modulate="true", maxRandomDelay="null")
2018-10-28 20:14:50,544 main DEBUG Building Plugin[name=Policies, class=org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy].
2018-10-28 20:14:50,545 main DEBUG createPolicy(={TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=true)})
2018-10-28 20:14:50,545 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.RollingFileAppender].
2018-10-28 20:14:50,549 main DEBUG RollingFileAppender$Builder(fileName="/A/B/c-web/c-web.log", filePattern="/A/B/c-web/archive/c-web_%d{yyyyMMdd}.log.gz", append="null", locking="null", Policies(CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=true)])), DefaultRolloverStrategy(DefaultRolloverStrategy(min=1, max=7, useMax=true)), advertise="null", advertiseUri="null", createOnDemand="null", filePermissions="null", fileOwner="null", fileGroup="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n), name="fileLogger", Configuration(properties_configuration), Filter=null)
2018-10-28 20:14:50,554 main DEBUG Starting RollingFileManager /A/B/c-web/c-web.log
2018-10-28 20:14:50,556 main DEBUG PluginManager 'FileConverter' found 2 plugins
2018-10-28 20:14:50,557 main DEBUG Setting prev file time to 2018-10-28T19:16:05.000+0530
2018-10-28 20:14:50,559 main DEBUG Initializing triggering policy CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=true)])
2018-10-28 20:14:50,560 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2018-10-28 20:14:50,561 main DEBUG PatternLayout$Builder(pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n", PatternSelector=null, Configuration(properties_configuration), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2018-10-28 20:14:50,561 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2018-10-28 20:14:50,563 main DEBUG ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n), name="consoleLogger", Configuration(properties_configuration), Filter=null)
2018-10-28 20:14:50,564 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2018-10-28 20:14:50,565 main DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2018-10-28 20:14:50,565 main DEBUG createAppenders(={fileLogger, consoleLogger})
2018-10-28 20:14:50,566 main DEBUG Configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration#23cd925 initialized
2018-10-28 20:14:50,566 main DEBUG Starting configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration#23cd925
2018-10-28 20:14:50,567 main DEBUG Started configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration#23cd925 OK.
2018-10-28 20:14:50,567 main DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2018-10-28 20:14:50,568 main DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
2018-10-28 20:14:50,568 main DEBUG Appender DefaultConsole-1 stopped with status true
2018-10-28 20:14:50,568 main DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration#699259d8 OK
2018-10-28 20:14:50,611 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd
2018-10-28 20:14:50,613 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=StatusLogger
2018-10-28 20:14:50,615 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=ContextSelector
2018-10-28 20:14:50,618 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=Loggers,name=
2018-10-28 20:14:50,619 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=Loggers,name=com.x
2018-10-28 20:14:50,620 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=Appenders,name=fileLogger
2018-10-28 20:14:50,621 main DEBUG Registering MBean org.apache.logging.log4j2:type=6be184cd,component=Appenders,name=consoleLogger
2018-10-28 20:14:50,623 main DEBUG org.apache.logging.log4j.core.util.SystemClock does not support precise timestamps.
2018-10-28 20:14:50,623 main DEBUG Reconfiguration complete for context[name=6be184cd] at URI <project-path>/target/classes/log4j2.properties (org.apache.logging.log4j.core.LoggerContext#ac76de5) with optional ClassLoader: null
2018-10-28 20:14:50,623 main DEBUG Shutdown hook enabled. Registering a new one.
2018-10-28 20:14:50,624 main DEBUG LoggerContext[name=6be184cd, org.apache.logging.log4j.core.LoggerContext#ac76de5] started OK.
2018-10-28 20:14:50,971 main DEBUG Using configurationFactory org.apache.logging.log4j.core.config.ConfigurationFactory$Factory#7ae5dec6
2018-10-28 20:14:50,974 main INFO Log4j appears to be running in a Servlet environment, but there's no log4j-web module available. If you want better web container support, please add the log4j-web JAR to your web archive or server lib directory.
Please let me know if you need any other information.
appreciate your help. Thanks in advance.
It turned out to be pretty simple.Spring boot was not loading the log4j2 configuration file properly during the Application starup.I just had to explicitly mention it.
I was able to get it working by adding
logging.config=src/main/resources/log4j2.properties
to my application.properties file.
Have some Spring Boot Integrationtests, e.g.:
#RunWith(SpringRunner.class)
#SpringBootTest
public class SupplierToSapInvoiceIntegrationTest {
...
}
All tests are successful when running locally, but on bamboo all tests fail. The Log says:
build 05-Mai-2017 15:20:46 2017-05-05 15:20:46.943 INFO 6556 ---
[ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Neither
#ContextConfiguration nor #ContextHierarchy found for test class
[com.odm.integration.SupplierToSapIntegrationTest], using
SpringBootContextLoader build 05-Mai-2017 15:20:46 2017-05-05
15:20:46.943 INFO 6556 --- [ Test worker]
o.s.t.c.support.AbstractContextLoader : Could not detect default
resource locations for test class
[com.odm.integration.SupplierToSapIntegrationTest]: no resource found
for suffixes {-context.xml, Context.groovy}. build 05-Mai-2017
15:20:46 2017-05-05 15:20:46.943 INFO 6556 --- [ Test worker]
t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default
configuration classes for test class
[com.odm.integration.SupplierToSapIntegrationTest]:
SupplierToSapIntegrationTest does not declare any static, non-private,
non-final, nested classes annotated with #Configuration.
build 05-Mai-2017 15:20:46 2017-05-05 15:20:46.943 INFO 6556 ---
[ Test worker] .b.t.c.SpringBootTestContextBootstrapper : Found
#SpringBootConfiguration com.odm.OdmBackendApplication for test class
com.odm.integration.SupplierToSapIntegrationTest build 05-Mai-2017
15:20:46 2017-05-05 15:20:46.943 INFO 6556 --- [ Test worker]
.b.t.c.SpringBootTestContextBootstrapper : Loaded default
TestExecutionListener class names from location
[META-INF/spring.factories]:
[org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener,
org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener,
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.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]
build 05-Mai-2017 15:20:46 2017-05-05 15:20:46.943 INFO 6556 ---
[ Test worker] .b.t.c.SpringBootTestContextBootstrapper : 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] build 05-Mai-2017 15:20:46
2017-05-05 15:20:46.943 INFO 6556 --- [ Test worker]
.b.t.c.SpringBootTestContextBootstrapper : Using
TestExecutionListeners:
[org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#7beec6bf,
org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#79dadc3e,
org.springframework.test.context.support.DirtiesContextTestExecutionListener#128f4f9c,
org.springframework.test.context.transaction.TransactionalTestExecutionListener#dad26fb,
org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#fbd2cf,
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#2fefc5c2,
org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#47749c0c,
org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#230af0e7,
org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#7db923e3,
org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#2c293843,
org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#4f5e5536]
Any idea, help? THX!!
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...).