Failed to Load ApplicationContext during Spring unit test - spring

I am trying to run a Junit functional test using Springs java-config for my application context. I am not sure if it is a problem with Spring or Junit... just not sure.. The application runs fine on my local server (hitting the db), but when I try to run my test it bombs out.
I just moved from xml to java config so I can always import my xml context files (which I know works in my tests) but going forward I would rather just use my java config.
My Test Class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = { AppConfig.class, ServletConfig.class })
#EnvironmentConfiguration(db2Enabled = true)
public class EventDAOTest {
The StackTrace
Feb 4, 2014 11:51:45 AM com.aoins.config.CachingPropertyFileReader <clinit>
SEVERE: ERROR - Configuration Framework not detected!
Feb 4, 2014 11:51:45 AM com.aoins.config.CachingPropertyFileReader readFile
SEVERE: Unable to build property reference for: (common).
2014-02-04 11:51:45,510 | DEBUG | : | LoggerConfigurer | Msg: Log4j configured with: 'C:/javalog/log4jPCProperties.xml'
2014-02-04 11:51:48,248 | INFO | : | EnvironmentConfigurer | Msg: DB2 Connection was established
2014-02-04 11:51:48,279 | INFO | : | EnvironmentConfigurer | Msg: CICS Connection was established
2014-02-04 11:51:48,279 | INFO | : | EnvironmentConfigurer | Msg: JMS Connection was NOT established according to the configuration
2014-02-04 11:51:48,279 | INFO | : | EnvironmentConfigurer | Msg: EMail Connection was NOT established according to the configuration
Feb 4, 2014 11:51:48 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext#215d215d: startup date [Tue Feb 04 11:51:48 EST 2014]; root of context hierarchy
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associates],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associate.AssociateDataController.retrieveAssociates(java.lang.String)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associateFilterTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterDataController.retrieveEventFilterTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associateFilterTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterDataController.retrieveEventFilterType(java.lang.String) throws com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/dateFilterTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.datefiltertype.DateFilterDataController.retrieveEventFilterTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/dateFilterTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.datefiltertype.DateFilterDataController.retrieveEventFilterType(java.lang.String) throws com.aoins.sales.eventplanning.datefiltertype.DateFilterTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/departments/{pDepartmentCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.department.DepartmentDataController.retrieveDepartment(java.lang.String) throws com.aoins.sales.eventplanning.department.DepartmentNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/divisions],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.division.DivisionDataController.retrieveDivisionsDepartments()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.aoins.sales.eventplanning.events.EventController.showEvents()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[//Test],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.aoins.sales.eventplanning.events.EventController.showTests()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events/{pEventId}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.retrieveEvent(java.lang.Integer)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events],methods=[GET],params=[page && associateFilter && dateFilter],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.retrieveFiltered(com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterType,com.aoins.sales.eventplanning.datefiltertype.DateFilterType,java.lang.Integer,com.aoins.sales.user.User)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events],methods=[POST],params=[],headers=[],consumes=[application/json],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.saveEvent(com.aoins.sales.eventplanning.events.EventBeanImpl,com.aoins.sales.user.User) throws com.aoins.sales.eventplanning.events.EventException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/Public/events],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public java.util.List<com.aoins.sales.eventplanning.events.Event> com.aoins.sales.eventplanning.events.EventDataPublicController.doList()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/Public/events/{pEventId}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public com.aoins.sales.eventplanning.events.Event com.aoins.sales.eventplanning.events.EventDataPublicController.doRetrieve(java.lang.Integer)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/eventTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.eventtype.EventTypeDataController.retrieveEventTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/eventTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.eventtype.EventTypeDataController.retrieveEventType(java.lang.String) throws com.aoins.sales.eventplanning.eventtype.EventTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#20c820c8] to prepare test instance [com.aoins.sales.eventplanning.events.EventDAOTest#f7e0f7e]
Throwable occurred: java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:326)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
at com.aoins.func.tester.AOSpringFunctionalTester.run(AOSpringFunctionalTester.java:48)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:121)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 26 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
... 41 more
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at java.lang.Throwable.<init>(Throwable.java:67)
at org.springframework.util.Assert.notNull(Assert.java:111)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:330)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f.CGLIB$defaultServletHandlerMapping$22(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f$$FastClassByCGLIB$$ff8cbba8.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:326)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f.defaultServletHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 42 more
So it appears that it is not finding the configuration framework, but I have been following the reference guides and API... not sure what I am missing or not configuring correctly. I am using Spring 4.0, Junit 4.10
Also, for each test it throws this error. That to me means it is trying to load the ApplicationContext again (prepareRefresh)... once for each #Test -- that also doesn't make sense to me...
Here are some resources:
ContextConfiguration API
Spring Reference Guide
Spring blog post

I moved from spring 3.2.0 to 4.0.3 and had to update my javax.servlet dependency (in maven) from servlet 2.5 to servlet 3.0.1. The final dependency was
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
Then it worked

You'll need to annotate your test class with
#WebAppConfiguration
so that the test environment provides your WebApplicationContext with a mock ServletContext required by your MVC configuration.

Since a couple people mentioned Servlet version issues:
As of Spring 4.0 the set of mocks is now based on the Servlet 3.0 API.
You have two options:
use 3.2.x spring-test dependency
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.14.RELEASE</version>
<scope>test</scope>
</dependency>
upgrade to servlet 3.0
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>

In gradle
testCompile 'javax.servlet:javax.servlet-api:3.1.0'
Note: this works for me even though I'm testing against Google App Engine (servlet 2.4) Because it is only used for tests.
https://jira.spring.io/browse/SPR-11049

the way to solve such problems -
try to force import of the notFoundClass manually, by smth like:
Class c = javax.servlet.SessionCookieConfig.class;
so Idea+Maven suggested me to add maven dependency, i agreed. And suddenly in pom.xml the code appeared:
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-servlet_3.0_spec</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
then i removed "Class c = javax.servlet.SessionCookieConfig.class;" - there is no need in it, rather than to load necessary dependency.

You can add a MockServletContext to your test applicationContext.
The MockServletContext can be found in spring-test.jar (or maven dependency). You should (obviously) not use this in production, but only register it in a context that you include in your test context.

Use #ActiveProfiles({"{test", "default"}) annotation

Related

Spring Boot 2.1 web-app does not work when deploy to standalone Apache Tomcat web server

I have a traditional project convert to Spring Boot,and it needs a custom listener to load the configuration file which referenced as static global variable in controller, it works well when I add the custom listener to ServletListenerRegistrationBean with the embedded tomcat.However,the custom listener does not work when the project deployed by traditional war package,and lead to startup failed.
This is a simplified demo https://github.com/xuande/spring-boot-demo
#RestController
public class ConfigController {
private Map<String, Object> configMap = ScaComponentFactory.getComponent();
#GetMapping("/properties/{key}")
public Object getConfig(#PathVariable("key") String key) {
return configMap.get(key);
}
}
public class ScaContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
System.out.println("start listener ...");
ScaComponentFactory.map = new HashMap<>();
ScaComponentFactory.map.put("test", "this is a demo");
}
public void contextDestroyed(ServletContextEvent sce) {
ScaComponentFactory.map.clear();
ScaComponentFactory.map = null;
}
}
public class ScaComponentFactory {
protected static Map<String, String> map = null;
public static String getComponent(String key) {
return map.get(key);
}
public static Map<String, Object> getComponent() {
return Collections.unmodifiableMap(map);
}
}
Main class
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public ServletListenerRegistrationBean<?> scaListenerRegistrationBean() {
ServletListenerRegistrationBean<ScaContextListener> registration = new ServletListenerRegistrationBean<ScaContextListener>();
registration.setListener(new ScaContextListener());
return registration;
}
}
With embedded tomcat works well
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-07-03 17:25:20.465 INFO 379676 --- [ main] org.spring.demo.Application : Starting Application on xuande00 with PID 379676 (G:\git\spring-boot-demo\target\classes started by xuande in G:\git\spring-boot-demo)
2019-07-03 17:25:20.465 INFO 379676 --- [ main] org.spring.demo.Application : No active profile set, falling back to default profiles: default
2019-07-03 17:25:23.481 INFO 379676 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 5050 (http)
2019-07-03 17:25:23.568 INFO 379676 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-07-03 17:25:23.568 INFO 379676 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.16]
2019-07-03 17:25:23.584 INFO 379676 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_144\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk1.8.0_111/bin/../jre/bin/server;C:/Program Files/Java/jdk1.8.0_111/bin/../jre/bin;C:/Program Files/Java/jdk1.8.0_111/bin/../jre/lib/amd64;D:\Program Files (x86)\NetSarang\Xshell 6\;d:\program files\graphicsmagick-1.3.30-q16;C:\Program Files\Java\jdk1.8.0_111\bin;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Windows\CCM;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Program Files (x86)\Pandoc\;D:\Program Files\apache-maven-3.5.2\bin;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;D:\Program Files\Microsoft VS Code\bin;D:\Program Files\Redis\;C:\Users\xuande\AppData\Local\Microsoft\WindowsApps;C:\Users\xuande\AppData\Roaming\npm;C:\Program Files (x86)\Pandoc\;D:\Program Files\hadoop-2.7.4\bin;D:\Program Files\gradle-4.6\bin;;E:\eclipse-loushang;;.]
2019-07-03 17:25:24.006 INFO 379676 --- [ main] org.apache.jasper.servlet.TldScanner : 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.
2019-07-03 17:25:24.006 INFO 379676 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-07-03 17:25:24.006 INFO 379676 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3447 ms
start listener ...
2019-07-03 17:25:24.428 INFO 379676 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-03 17:25:25.037 INFO 379676 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 5050 (http) with context path ''
2019-07-03 17:25:25.075 INFO 379676 --- [ main] org.spring.demo.Application : Started Application in 5.512 seconds (JVM running for 6.3)
With standalone tomcat not working
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Server version: Apache Tomcat/8.5.24
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Server built: Nov 27 2017 13:05:30 UTC
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Server number: 8.5.24.0
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: OS Name: Windows 10
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: OS Version: 10.0
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Architecture: amd64
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Java Home: C:\Program Files\Java\jdk1.8.0_144\jre
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: JVM Version: 1.8.0_144-b01
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: JVM Vendor: Oracle Corporation
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: CATALINA_BASE: G:\apache-tomcat-8.5.24
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: CATALINA_HOME: G:\apache-tomcat-8.5.24
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Command line argument: -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:8783
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Command line argument: -Dcatalina.base=G:\apache-tomcat-8.5.24
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Command line argument: -Dcatalina.home=G:\apache-tomcat-8.5.24
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Command line argument: -Dwtp.deploy=G:\apache-tomcat-8.5.24\wtpwebapps
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Command line argument: -Djava.endorsed.dirs=G:\apache-tomcat-8.5.24\endorsed
July 03, 2019 5:21:35 PM org.apache.catalina.startup.VersionLoggerListener log
Info: Command line argument: -Dfile.encoding=UTF-8
July 03, 2019 5:21:35 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
Info: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_144\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.8.0_144\jre\bin;C:/Program Files/Java/jdk1.8.0_111/bin/../jre/bin/server;C:/Program Files/Java/jdk1.8.0_111/bin/../jre/bin;C:/Program Files/Java/jdk1.8.0_111/bin/../jre/lib/amd64;D:\Program Files (x86)\NetSarang\Xshell 6\;d:\program files\graphicsmagick-1.3.30-q16;C:\Program Files\Java\jdk1.8.0_111\bin;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Windows\CCM;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Program Files (x86)\Pandoc\;D:\Program Files\apache-maven-3.5.2\bin;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;D:\Program Files\Microsoft VS Code\bin;D:\Program Files\Redis\;C:\Users\xuande\AppData\Local\Microsoft\WindowsApps;C:\Users\xuande\AppData\Roaming\npm;C:\Program Files (x86)\Pandoc\;D:\Program Files\hadoop-2.7.4\bin;D:\Program Files\gradle-4.6\bin;;E:\eclipse-loushang;;.]
July 03, 2019 5:21:35 PM org.apache.coyote.AbstractProtocol init
Info: Initializing ProtocolHandler ["http-nio-9080"]
July 03, 2019 5:21:36 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
Info: Using a shared selector for servlet write/read
July 03, 2019 5:21:36 PM org.apache.coyote.AbstractProtocol init
Info: Initializing ProtocolHandler ["ajp-nio-9019"]
July 03, 2019 5:21:36 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
Info: Using a shared selector for servlet write/read
July 03, 2019 5:21:36 PM org.apache.catalina.startup.Catalina load
Info: Initialization processed in 1660 ms
July 03, 2019 5:21:36 PM org.apache.catalina.core.StandardService startInternal
Info: Starting service [Catalina]
July 03, 2019 5:21:36 PM org.apache.catalina.core.StandardEngine startInternal
Info: Starting Servlet Engine: Apache Tomcat/8.5.24
July 03, 2019 5:21:42 PM org.apache.jasper.servlet.TldScanner scanJars
Info: 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.
July 03, 2019 5:21:43 PM org.apache.catalina.core.ApplicationContext log
Info: 2 Spring WebApplicationInitializers detected on classpath
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-07-03 17:21:44.556 INFO 398420 --- [ost-startStop-1] org.spring.demo.Application : Starting Application on xuande00 with PID 398420 (G:\git\spring-boot-demo\target\demo\WEB-INF\classes started by xuande in E:\eclipse-loushang)
2019-07-03 17:21:44.556 INFO 398420 --- [ost-startStop-1] org.spring.demo.Application : No active profile set, falling back to default profiles: default
2019-07-03 17:21:46.041 INFO 398420 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/demo] : Initializing Spring embedded WebApplicationContext
2019-07-03 17:21:46.056 INFO 398420 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1422 ms
2019-07-03 17:21:46.667 WARN 398420 --- [ost-startStop-1] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configController' defined in file [G:\git\spring-boot-demo\target\demo\WEB-INF\classes\org\spring\demo\controller\ConfigController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.spring.demo.controller.ConfigController]: Constructor threw exception; nested exception is java.lang.NullPointerException
2019-07-03 17:21:46.683 INFO 398420 --- [ost-startStop-1] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-07-03 17:21:46.699 ERROR 398420 --- [ost-startStop-1] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configController' defined in file [G:\git\spring-boot-demo\target\demo\WEB-INF\classes\org\spring\demo\controller\ConfigController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.spring.demo.controller.ConfigController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1287) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1181) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:157) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:137) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:91) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:171) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196) [catalina.jar:8.5.24]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.5.24]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419) [catalina.jar:8.5.24]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) [catalina.jar:8.5.24]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_144]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.spring.demo.controller.ConfigController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1279) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 26 common frames omitted
Caused by: java.lang.NullPointerException: null
at java.util.Collections$UnmodifiableMap.<init>(Collections.java:1446) ~[na:1.8.0_144]
at java.util.Collections.unmodifiableMap(Collections.java:1433) ~[na:1.8.0_144]
at org.spring.demo.listener.ScaComponentFactory.getComponent(ScaComponentFactory.java:15) ~[classes/:na]
at org.spring.demo.controller.ConfigController.<init>(ConfigController.java:13) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 28 common frames omitted
#Configuration
public class ScaContextInitializer implements ServletContextInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("start listener ...");
ScaComponentFactory.map = new HashMap<>();
ScaComponentFactory.map.put("test", "this is a demo");
}
}
Both embedded tomcat and standalone tomcat work well using ServletContextInitializer instead of ServletContextListener

Spring not able to locate the xml configuration file

I tried by placing the springConfig.xml in the WEB_INF as well as src directory, but still getting the IOException.
Code:
public class DrawingApp {
public static void main(String[] args) {
//Triangle triangle = new Triangle();
ApplicationContext context = new
ClassPathXmlApplicationContext("springConfig.xml");
Triangle triangle = (Triangle) context.getBean("triangle");
triangle.draw();
((ClassPathXmlApplicationContext)context).close();
}
}
Exception:
Jul 23, 2018 11:33:18 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#179d3b25: startup date [Mon Jul 23 11:33:18 IST 2018]; root of context hierarchy
Jul 23, 2018 11:33:18 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [springConfig.xml]
Jul 23, 2018 11:33:19 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from URL [file:/D:/Learning/Workspace/Java%20Project/Spring2/SpringDemo/target/classes/trace-context.xml]
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [trace-context.xml]
Offending resource: class path resource [springConfig.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from URL [file:/D:/Learning/Workspace/Java%20Project/Spring2/SpringDemo/target/classes/trace-context.xml]; nested exception is java.io.FileNotFoundException: D:\Learning\Workspace\Java Project\Spring2\SpringDemo\target\classes\trace-context.xml (The system cannot find the file specified)
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at
org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:255)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:180)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:165)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:138)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304
You should specify where is the resource path located within your project. More on this link
https://maven.apache.org/pom.html#Resources

Web.xml still missing when deploying a Spring Boot RESTful Web Service to Tomcat

I am trying to deploy a RESTful Web Service built with Spring Boot into a Tomcat instance, with little success.
My software configuration is as follows: my computer is a Mac running OS X Yosemite 10.10.3, with Oracle Java JDK 8 1.8.0_45, Gradle 2.4 and Apache Tomcat 7.0.47. I use IntelliJ IDEA 14.1.4 as development platform.
I started by following this guide and I got a jar that initiates an embedded container which works as expected. Then I followed the document about converting a Spring Boot JAR Application to a WAR linked at the end of the other guide. I followed the instructions in Section 59.4 "Packaging executable jar and war files" and then those in the Section 74.1 "Create a deployable war file". According to the posts of a few other members of this site who were facing the same problem (here, here, here and here, just to name a few), I should be able now to create a create a WAR and deploy it on my Tomcat. Unfortunately, this is not the case.
The project contains the following 3 Java files: Application.java, Greeting.java and GreetingController.java. The first is as follows:
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
The second file contains the following:
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
And, finally, the latter file is:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/hello")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
The project also contains the following build.gradle file:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.4.RELEASE")
}
}
apply plugin: 'war'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
war {
baseName = 'rest'
// version = '0.1.0'
}
repositories {
mavenLocal()
mavenCentral()
}
configurations {
providedRuntime
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
testCompile("junit:junit")
}
Now, if I run the task "gradle war", I generate a WAR file of about 8 Mb. I can successfully deploy it to my local Tomcat, but when I point my browser to http://localhost:8080/rest/hello?name=World I got a blank page rather than the page with the expected JSON. If I run the task "gradle build" or "gradle bootRepackage", I get both a JAR and a WAR and their original versions. I'm mentioning these commands because I haven't seen them anywhere and they might be useful to know. The original versions are both around 8 Mb in size, while the JAR and the WAR of 12 Mb. If I deploy both WARs, I get no error messages but, again, no results in the browser. Somebody here suggested that the web.xml could be missing, and in fact no WAR actually contained such a file. I am saying so because my Tomcat is not very recent and for some reason I thought Spring Boot had to automatically create a web.xml out of the code and annotations above.
As suggested by #dunni in the comments, here are my Tomcat log files. First of all, catalina.log:
giu 24, 2015 10:35:01 AM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /usr/local/apache-tomcat-7.0.47/webapps/rest.war
Then localhost.log:
giu 24, 2015 10:35:02 AM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration#4dfaba52]
And finally manager.log:
giu 24, 2015 10:34:43 AM org.apache.catalina.core.ApplicationContext log
INFO: HTMLManager: list: Listing contexts for virtual host 'localhost'
giu 24, 2015 10:34:44 AM org.apache.catalina.core.ApplicationContext log
INFO: HTMLManager: list: Listing contexts for virtual host 'localhost'
giu 24, 2015 10:35:02 AM org.apache.catalina.core.ApplicationContext log
INFO: HTMLManager: list: Listing contexts for virtual host 'localhost'
The above content is what I get after deploy the WAR. Nothing changes if I subsequently try to connect to http://localhost:8080/, http://localhost:8080/rest/, http://localhost:8080/rest/hello or http://localhost:8080/rest/hello?name=World.
What is going on? What am I missing? Can you please explain me what is the problem and what have I to do to successfully deploy this toy service on Tomcat? Many thanks in advance.
Since the above logs were not really helpful, I tried to restart the Tomcat daemon and I got something more meaningful. Now I have the following files: catalina.log, catalina.out, host-manager.log (empty), launchd.stderr (empty), launchd.stdout, localhost_access_log.txt (empty), localhost.log and manager.log (empty). catalina.log and catalina.out now contains the following:
giu 24, 2015 11:11:49 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/stefano/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
giu 24, 2015 11:11:49 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
giu 24, 2015 11:11:49 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
giu 24, 2015 11:11:49 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 666 ms
giu 24, 2015 11:11:49 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
giu 24, 2015 11:11:49 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
giu 24, 2015 11:11:49 AM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /usr/local/apache-tomcat-7.0.47/webapps/Plakko.war
giu 24, 2015 11:11:51 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [574] milliseconds.
giu 24, 2015 11:11:51 AM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /usr/local/apache-tomcat-7.0.47/webapps/rest.war
giu 24, 2015 11:11:52 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /usr/local/apache-tomcat-7.0.47/webapps/docs
giu 24, 2015 11:11:52 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /usr/local/apache-tomcat-7.0.47/webapps/host-manager
giu 24, 2015 11:11:53 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /usr/local/apache-tomcat-7.0.47/webapps/manager
giu 24, 2015 11:11:53 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /usr/local/apache-tomcat-7.0.47/webapps/ROOT
giu 24, 2015 11:11:53 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
giu 24, 2015 11:11:53 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
giu 24, 2015 11:11:53 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3349 ms
launchd.stdout contains:
Wed Jun 24 11:11:48 CEST 2015
Starting Tomcat
Waiting for 89105
And localhost.log contains:
giu 24, 2015 11:11:52 AM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration#2d5eb959]
If I try to consume the Web Service, localhost_access_log.txt is updated with:
217.20.22.194 - - [24/Jun/2015:11:23:16 +0200] "GET / HTTP/1.1" 200 11444
217.20.22.194 - - [24/Jun/2015:11:23:19 +0200] "GET /rest/ HTTP/1.1" 404 5
217.20.22.194 - - [24/Jun/2015:11:23:19 +0200] "GET /rest/hello HTTP/1.1" 404 5
217.20.22.194 - - [24/Jun/2015:11:23:20 +0200] "GET /rest/hello?name=World HTTP/1.1" 404 5
Since I have the feeling that these logs are not really helpful, I tried to shutdown and startup Tomcat. In this case I find something interesting in catalina.log and catalina.out. The former:
giu 24, 2015 11:36:56 AM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /usr/local/apache-tomcat-7.0.47/webapps/rest.war
giu 24, 2015 11:36:59 AM org.apache.catalina.core.ContainerBase addChildInternal
SEVERE: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/rest]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:983)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1660)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.NoSuchMethodError: java.lang.reflect.Parameter.isNamePresent()Z
at org.springframework.core.StandardReflectionParameterNameDiscoverer.getParameterNames(StandardReflectionParameterNameDiscoverer.java:56)
at org.springframework.core.PrioritizedParameterNameDiscoverer.getParameterNames(PrioritizedParameterNameDiscoverer.java:65)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:182)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1139)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1042)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry$OptimizedBeanTypeRegistry.getFromFactory(BeanTypeRegistry.java:320)
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry.get(BeanTypeRegistry.java:162)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.collectBeanNamesForType(OnBeanCondition.java:158)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:147)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:119)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:94)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:45)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:102)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:190)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:148)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:124)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:318)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:239)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.context.web.SpringBootServletInitializer.run(SpringBootServletInitializer.java:117)
at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:108)
at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:68)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5423)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 10 more
giu 24, 2015 11:36:59 AM org.apache.catalina.startup.HostConfig deployWAR
SEVERE: Error deploying web application archive /usr/local/apache-tomcat-7.0.47/webapps/rest.war
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/rest]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:983)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1660)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
And the latter catalina.out:
giu 24, 2015 11:36:56 AM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /usr/local/apache-tomcat-7.0.47/webapps/rest.war
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.2.4.RELEASE)
2015-06-24 11:36:59.019 INFO 89274 --- [ost-startStop-1] o.s.boot.SpringApplication : Starting application on Mac-mini-di-Stefano.local with PID 89274 (/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-boot-1.2.4.RELEASE.jar started by stefano in /usr/local/apache-tomcat-7.0.47/bin)
2015-06-24 11:36:59.047 INFO 89274 --- [ost-startStop-1] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#34a13c2b: startup date [Wed Jun 24 11:36:59 CEST 2015]; root of context hierarchy
2015-06-24 11:36:59.648 INFO 89274 --- [ost-startStop-1] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/classes/, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/aopalliance-1.0.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/classmate-1.0.0.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/hibernate-validator-5.1.3.Final.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/jackson-annotations-2.4.0.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/jackson-core-2.4.6.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/jackson-databind-2.4.6.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/jboss-logging-3.1.3.GA.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/jcl-over-slf4j-1.7.12.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/jul-to-slf4j-1.7.12.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/log4j-over-slf4j-1.7.12.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/logback-classic-1.1.3.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/logback-core-1.1.3.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/slf4j-api-1.7.12.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/snakeyaml-1.14.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-aop-4.1.6.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-beans-4.1.6.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-boot-1.2.4.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-boot-autoconfigure-1.2.4.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-boot-starter-1.2.4.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-boot-starter-logging-1.2.4.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-boot-starter-web-1.2.4.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-context-4.1.6.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-core-4.1.6.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-expression-4.1.6.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-web-4.1.6.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/spring-webmvc-4.1.6.RELEASE.jar, file:/usr/local/apache-tomcat-7.0.47/webapps/rest/WEB-INF/lib/validation-api-1.1.0.Final.jar]
2015-06-24 11:36:59.663 ERROR 89274 --- [ost-startStop-1] o.s.boot.SpringApplication : Application startup failed
java.lang.NoSuchMethodError: java.lang.reflect.Parameter.isNamePresent()Z
at org.springframework.core.StandardReflectionParameterNameDiscoverer.getParameterNames(StandardReflectionParameterNameDiscoverer.java:56)
at org.springframework.core.PrioritizedParameterNameDiscoverer.getParameterNames(PrioritizedParameterNameDiscoverer.java:65)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:182)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1139)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1042)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry$OptimizedBeanTypeRegistry.getFromFactory(BeanTypeRegistry.java:320)
at org.springframework.boot.autoconfigure.condition.BeanTypeRegistry.get(BeanTypeRegistry.java:162)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.collectBeanNamesForType(OnBeanCondition.java:158)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:147)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:119)
at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:94)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:45)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:102)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:190)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:148)
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:124)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:318)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:239)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.context.web.SpringBootServletInitializer.run(SpringBootServletInitializer.java:117)
at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:108)
at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:68)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5423)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:983)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1660)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
By looking at these logs, I have the feeling that something is failing in the auto-magical process of Spring but unfortunately I don't know what and how to fix it. Any help?
What version of java are you using? The gradle file indicates you intend to use java 8, but this error indicates you are not...
java.lang.NoSuchMethodError: java.lang.reflect.Parameter.isNamePresent()
The Parameter class was not introduced until java 8. What version of java is your tomcat using?

Spring Injection for Strings using Groovy

This example was working and the only thing I think has changed is the version of java and groovy I have installed.
#Grab('org.springframework:spring-context:3.2.1.RELEASE')
#Grab('org.apache.commons:commons-lang3:3.1')
#GrabConfig(systemClassLoader = true)
import org.springframework.context.support.ClassPathXmlApplicationContext
def ctx = new ClassPathXmlApplicationContext("classpath:context.xml")
def su = ctx.getBean('su')
def result = su.swapCase('Fee Fi Fo Fum')
assert result == 'fEE fI fO fUM'
println "result = $result"
Here is the context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="su" class="org.apache.commons.lang3.StringUtils"/>
<bean id="data" class="java.lang.String"><constructor-arg value="Fee Fi Fo Fum"/></bean>
</beans>
If I comment out the second to the last line of the context file it runs.
This used to work and it does not work now. What am I doing now?
I'm running
Groovy 2.3.0-beta-2
Java 1.8.0_05.
This is the log/trace:
Mar 23, 2015 4:28:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#73d983ea: startup date [Mon Mar 23 16:28:26 PDT 2015]; root of context hierarchy
Mar 23, 2015 4:28:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [context.xml]
Mar 23, 2015 4:28:27 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#53dbe163: defining beans [su,data]; root of factory hierarchy
Caught: java.lang.IllegalArgumentException
java.lang.IllegalArgumentException
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:110)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:85)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at works.run(works.groovy:14)
Process compilation exited abnormally with code 1
You need at least Spring 4 in order to compile using Java 8.
Announced here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/new-in-4.0.html
You are using Spring 3.2, you must use Java 7.

Issues with Oracle JDBC with Hibernate... Sometimes

I'm having a bit of a unique issue.
I'm able to successfully connect and manage entities when running JUnit tests, but once I start my actual application, I get "Specified JDBC Driver oracle.jdbc.OracleDriver class not found."
What confuses me is that it is there. It works when running my JUnit Tests.
Any insights are appreciated!
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="db">
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#host:port/db</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.default_schema">db</property>
<property name="show_sql">true</property>
<mapping resource="org/entity/RunResultEntity.hbm.xml"/>
<mapping resource="org/entity/TransactionResultEntity.hbm.xml"/>
<mapping resource="org/entity/FailureResultEntity.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package org.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.*;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()
).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Exception thrown here!
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
pom.xml (dependency added to local repository)
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3.0</version>
<scope>provided</scope>
</dependency>
log
Oct 09, 2014 3:02:58 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Oct 09, 2014 3:02:58 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.1.Final}
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/RunResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/TransactionResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/FailureResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: db
Oct 09, 2014 3:02:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Initial SessionFactory creation failed.org.hibernate.HibernateException: Specified JDBC Driver oracle.jdbc.OracleDriver class not found
Exception in thread "main" java.lang.ExceptionInInitializerError
I found my problem. Lower in my pom.xml I had this little snippet
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
<classifier>tests</classifier>
</dependency>
The classifier was only giving access to my test suite. Removing the classifier fixed the issue.
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
</dependency>

Resources