SpringRunner ignores application properties - spring

I am trying to create Spring integration tests as follow:
#RunWith(SpringRunner::class)
#ActiveProfiles(profiles = ["Test"])
#ContextConfiguration(locations = ["classpath:**/applicationContext.xml"])
open class SimpleEntityIT {...}
applicationContact.xml contains:
<context:annotation-config/>
<context:spring-configured/>
<context:property-placeholder
ignore-resource-not-found="false"
location="classpath:application${spring.profiles.active}.properties,classpath:application.properties"/>
<context:component-scan base-package="net.goout"/>
The applicationContext is loaded, but it seems it is mostly ignored. Beans are not constructed via component-scan and the application.properties are completely ignored, no mention in logs:
2018-01-26 20:09:26,131 DEBUG Resolved location pattern [classpath:**/applicationContext.xml] to resources []
2018-01-26 20:09:26,132 DEBUG Loaded 0 bean definitions from location pattern [classpath:**/applicationContext.xml]
2018-01-26 20:09:26,167 INFO Refreshing org.springframework.context.support.GenericApplicationContext#aecb35a: startup date [Fri Jan 26 20:09:26 CET 2018]; root of context hierarchy
2018-01-26 20:09:26,167 DEBUG Bean factory for org.springframework.context.support.GenericApplicationContext#aecb35a: org.springframework.beans.factory.support.DefaultListableBeanFactory#20d3d15a: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory]; root of factory hierarchy
2018-01-26 20:09:26,198 DEBUG Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
2018-01-26 20:09:26,198 DEBUG Creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
2018-01-26 20:09:26,225 DEBUG Eagerly caching bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' to allow for resolving potential circular references
2018-01-26 20:09:26,231 DEBUG Finished creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
What am I not getting?
EDIT: Not event component-scan beans are not constructed, but really no beans are constructed – even those defined by <bean> in applicationContext.xml. It seems its content is just ignored even though it is correctly found.

As per the latest comments i believe this issue is solved, but even then couple of quick observations and alternatives :
a) You did not get an error on missing resource is because of below attr,i would suggest making it true to identify issues early on :
ignore-resource-not-found="false"
Also, you could use below :
#PropertySource(value = "xyz.properties", ignoreResourceNotFound = true)
b) Completely unrelated but :
#ActiveProfiles(profiles = ["Test"])
Could be written as :
#ActiveProfiles({"Test","QA"})
or in your application-test.properties
spring.profiles.active=Test,QA
c)For placing applicationContext.xml ,an alternative can also be placed in web.xml :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/*.xml</param-value>
</context-param>
(Although, annotation with specifying the exact location with #ContextConfiguration is completely fine as well! )
And above all , if you are using Annotation based configs, i would advice Spring boot :-)
Hope it helps!!

You should not copy applicationContext.xml to /test/resources yourself. Allow this to maven
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
</build>

Related

AspectJ LTW (weaving) not working with Spring Boot

I'm on Spring Boot 2.1.2.RELEASE - Java 11 - Fat JAR
Following the documentation, I have:
added the required dependencies to the Gradle build
implementation 'org.springframework.boot:spring-boot-starter-aop'
implementation 'org.aspectj:aspectjrt:1.9.2'
implementation 'org.aspectj:aspectjweaver:1.9.2'
enabled LoadTimeWeaving
#SpringBootApplication
#EnableLoadTimeWeaving
public class MyApplication { ... }
provided the aop.xml under META-INF
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver>
<!-- only weave classes in our application-specific packages -->
<include within="my.base.package.*" />
</weaver>
<aspects>
<!-- weave in just this aspect -->
<aspect name="my.base.package.spring.aop.MyAspects" />
</aspects>
</aspectj>
created the new #Aspect class
#Aspect
public class MyAspects {
#Around("methodsToBeProfiled()")
public Object profile(final ProceedingJoinPoint pjp) throws Throwable {
final var sw = new StopWatch(getClass().getSimpleName());
try {
sw.start(pjp.getSignature().getName());
return pjp.proceed();
} finally {
sw.stop();
System.out.println(sw.prettyPrint());
}
}
#Pointcut("execution(* my.base.package.other.MyClass.*(..))")
public void methodsToBeProfiled() {}
}
added the Jar for instrumentation
-javaagent:/home/myuser/spring-instrument-5.1.5.RELEASE.jar
Log, which as you see, show MyAspects as recognized
[AppClassLoader#2c13da15] info AspectJ Weaver Version 1.9.2 built on Wednesday Oct 24, 2018 at 15:43:33 GMT
[AppClassLoader#2c13da15] info register classloader jdk.internal.loader.ClassLoaders$AppClassLoader#2c13da15
[AppClassLoader#2c13da15] info using configuration /home/edoardo/IdeaProjects/scheduler/scheduler-engine/out/production/resources/META-INF/aop.xml
[AppClassLoader#2c13da15] info using configuration file:/home/edoardo/.gradle/caches/modules-2/files-2.1/org.springframework/spring-aspects/5.1.5.RELEASE/3bb95e05b646ef93e2a4cf0b600924c2979fc723/spring-aspects-5.1.5.RELEASE.jar!/META-INF/aop.xml
[AppClassLoader#2c13da15] info register aspect my.base.package.spring.aop.MyAspects
[AppClassLoader#2c13da15] info register aspect org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect
[AppClassLoader#2c13da15] info register aspect org.springframework.scheduling.aspectj.AnnotationAsyncExecutionAspect
[AppClassLoader#2c13da15] info register aspect org.springframework.transaction.aspectj.AnnotationTransactionAspect
[AppClassLoader#2c13da15] info register aspect org.springframework.transaction.aspectj.JtaAnnotationTransactionAspect
[AppClassLoader#2c13da15] info deactivating aspect 'org.springframework.transaction.aspectj.JtaAnnotationTransactionAspect' as it requires type 'javax.transaction.Transactional' which cannot be found on the classpath
[AppClassLoader#2c13da15] info register aspect org.springframework.cache.aspectj.AnnotationCacheAspect
[AppClassLoader#2c13da15] info register aspect org.springframework.cache.aspectj.JCacheCacheAspect
[AppClassLoader#2c13da15] info deactivating aspect 'org.springframework.cache.aspectj.JCacheCacheAspect' as it requires type 'org.springframework.cache.jcache.interceptor.JCacheAspectSupport' which cannot be found on the classpath
[AppClassLoader#2c13da15] info deactivating aspect 'org.springframework.cache.aspectj.JCacheCacheAspect' as it requires type 'javax.cache.annotation.CacheResult' which cannot be found on the classpath
[AppClassLoader#2c13da15] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified
However MyAspects is never instantiated (so no debug), and methods are not being weaved with my aspect code.
Did I miss something?
Edit: seems both Jars, aspectjweaver and spring-instrument are required as agents. Is this normal?
You do need the aspectjweaver agent jar. You don't need spring-instrument (ever for a fat jar - AFAIK it was used in app servers to work around some historical issues with their class loaders). You also don't need to #EnableLoadTimeWeaving (also an app server feature, redundant if you control the agent). Also (minor niggle) aspectjrt is a transitive dependency of aspectjweaver, so you don't need both. So you have it working it seems, even though you have done more work than you needed. Sample Spring Boot apps with various weaving options: here.

Spring Boot Does Not Seem to Start

I am trying to get a Spring Boot WAR to deploy to a private Tomcat 7.0.68 instance hosted by DailyRazor. I cannot figure out why the Spring Boot application will not work. I do not seem to get any errors. Locally, I have gotten this to work with STS 3.8.4, Tomcat 7.0.78, Tomcat 8.5.11, and a couple other versions of Tomcat.
I never see the Spring Boot banner display on the DailyRazor instance nor much of the other logging indicating that my Spring Boot application is starting and loading all of the beans. This is the only logging I see:
INFO main org.apache.catalina.core.StandardService - Stopping service Catalina
INFO main org.apache.catalina.core.AprLifecycleListener - The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/local/tomcat/users/user_id/jdk/jre/lib/amd64/server:/usr/local/tomcat/users/user_id/jdk/jre/lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
INFO main org.apache.catalina.startup.Catalina - Initialization processed in 2299 ms
INFO main org.apache.catalina.core.StandardService - Starting service Catalina
INFO main org.apache.catalina.core.StandardEngine - Starting Servlet Engine: Apache Tomcat/7.0.68
INFO foobar.com-startStop-1 org.apache.catalina.startup.TldConfig - 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.
INFO foobar.com-startStop-1 org.apache.catalina.util.SessionIdGeneratorBase - Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [271] milliseconds.
INFO foobar.com-startStop-1 org.apache.catalina.startup.HostConfig - Deploying web application archive /home/user_id/tomcat/webapps/foobar.com/ROOT.war
INFO foobar.com-startStop-1 org.apache.catalina.startup.TldConfig - 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.
INFO foobar.com-startStop-1 org.apache.catalina.startup.HostConfig - Deployment of web application archive /home/user_id/tomcat/webapps/foobar.com/ROOT.war has finished in 1,603 ms
INFO foobar.com-startStop-1 org.apache.catalina.startup.HostConfig - Deploying web application archive /home/user_id/tomcat/webapps/foobar.com/plant-service-0.0.1-SNAPSHOT.war
INFO foobar.com-startStop-1 org.apache.catalina.startup.TldConfig - 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.
INFO foobar.com-startStop-1 org.apache.catalina.core.ContainerBase.[Catalina].[foobar.com].[/plant-service-0.0.1-SNAPSHOT] - 3 Spring WebApplicationInitializers detected on classpath
INFO foobar.com-startStop-1 org.apache.catalina.core.ContainerBase.[Catalina].[foobar.com].[/plant-service-0.0.1-SNAPSHOT] - Initializing Spring embedded WebApplicationContext
INFO foobar.com-startStop-1 org.apache.catalina.startup.HostConfig - Deployment of web application archive /home/user_id/tomcat/webapps/foobar.com/plant-service-0.0.1-SNAPSHOT.war has finished in 21,769 ms
INFO main org.apache.catalina.startup.Catalina - Server startup in 26534 ms
INFO ajp-bio-127.0.0.1-9592-exec-1 org.apache.catalina.core.ContainerBase.[Catalina].[foobar.com].[/plant-service-0.0.1-SNAPSHOT] - Initializing Spring FrameworkServlet 'dispatcherServlet'
I have following the instructions for packaging as a WAR, extending SpringBootServletInitializer, overriding configure(...), etc. Again, this all works locally on multiple versions of Tomcat. I have tried to adjust the logging, but I do not see anything useful.
Any hints? Suggestions?
EDIT
Not sure if it is related, but when shutting down Tomcat, I see the following:
INFO main org.apache.catalina.core.StandardService - Stopping service Catalina
ERROR foobar.com-startStop-2 org.apache.catalina.loader.WebappClassLoaderBase - The web application [] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
INFO foobar.com-startStop-2 org.apache.catalina.core.ContainerBase.[Catalina].[foobar.com].[/plant-service-0.0.1-SNAPSHOT] - Destroying Spring FrameworkServlet 'dispatcherServlet'
INFO foobar.com-startStop-2 org.apache.catalina.core.ContainerBase.[Catalina].[foobar.com].[/plant-service-0.0.1-SNAPSHOT] - Closing Spring root WebApplicationContext
ERROR foobar.com-startStop-2 org.apache.catalina.loader.WebappClassLoaderBase - The web application [/plant-service-0.0.1-SNAPSHOT] registered the JDBC driver [com.mysql.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.
ERROR foobar.com-startStop-2 org.apache.catalina.loader.WebappClassLoaderBase - The web application [/plant-service-0.0.1-SNAPSHOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
Could you please ensure you did all of this correctly ?
From Create a deployable war file (Spring boot documentation) :
Create a deployable war file
The first step in producing a deployable war file is to provide a
SpringBootServletInitializer subclass and override its configure
method. This makes use of Spring Framework’s Servlet 3.0 support and
allows you to configure your application when it’s launched by the
servlet container. Typically, you update your application’s main class
to extend SpringBootServletInitializer:
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
The next step is to update your build configuration so that your
project produces a war file rather than a jar file. If you’re using
Maven and using spring-boot-starter-parent (which configures Maven’s
war plugin for you) all you need to do is to modify pom.xml to
change the packaging to war:
<packaging>war</packaging>
EDIT
Do you have spring-boot-starter-web and spring-boot-starter-tomcat dependencies ?
To build a war file that is both executable and deployable into an
external container you need to mark the embedded container
dependencies as “provided”, e.g:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- ... -->
<packaging>war</packaging>
<!-- ... -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- ... -->
</dependencies>
</project>

Application context being loaded twice - Spring Boot

I have a fairly simple setup. A maven project with 3 modules : core/webapp/model. I'm using Spring boot to gear up my application. In webapp, i have a simple class WebappConfig as follows:
#Configuration
#EnableAutoConfiguration
#ComponentScan(excludeFilters = #ComponentScan.Filter(Configuration.class))
public class WebappConfig {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(WebappConfig.class);
app.setAdditionalProfiles("dev");
app.run(args);
}
}
and few classes in core/model module. My container-application point is :
public class AbcdXml extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebappConfig.class);
}
}
And no web.xml! My model's pom has following spring boot related dependency :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Core's pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
Now running WebappConfig via Run as -> Java application works perfectly but i need to deploy the project as a war on tomcat7. Webapp's packaging is war. There is no tomcat provided jar's in lib except tomcat-jdbc and tomcat-tuli jar(Shouldn't be an issue?).
When i deploy my abcd.war, applicationcontext is getting loaded twice and result in following error stracktrace :
2014-06-27 11:06:08.445 INFO 23467 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/abcd] : Initializing Spring embedded WebApplicationContext
2014-06-27 11:06:08.446 INFO 23467 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 19046 ms
2014-06-27 11:06:21.308 INFO 23467 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2014-06-27 11:06:21.313 INFO 23467 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'errorPageFilter' to: [/*]
2014-06-27 11:06:21.314 INFO 23467 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2014-06-27 11:06:26.073 INFO 23467 --- [ost-startStop-1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2014-06-27 11:06:26.127 INFO 23467 --- [ost-startStop-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2014-06-27 11:06:26.511 INFO 23467 --- [ost-startStop-1] org.hibernate.Version : HHH000412: Hibernate Core {4.3.1.Final}
2014-06-27 11:06:26.521 INFO 23467 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2014-06-27 11:06:26.527 INFO 23467 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
//some info messages from spring boot
2014-06-27 11:07:31.664 INFO 23467 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-06-27 11:07:33.095 INFO 23467 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-06-27 11:07:33.096 INFO 23467 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-06-27 11:07:36.080 INFO 23467 --- [ost-startStop-1] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2014-06-27 11:08:49.583 INFO 23467 --- [ost-startStop-1] o.s.boot.SpringApplication : Started application in 183.152 seconds (JVM running for 210.258)
2014-06-27 11:12:29.229 ERROR 23467 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/abcd] : 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:277)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
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:976)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1653)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
There is no web.xml as i mentioned earlier.
Few interesting things that i can't figure out why :
After exploding the war, tomcat somehow create a ROOT folder with default web.xml[Must be Spring boot misconfiguration. How can i correct it? Pointers please?]
Even if i return same 'application' SpringApplicationBuilder in AbcdXml.java, i am facing the same issue of applicationcontext being loaded twice.
Thanks for your help!
EDIT 1:
Content of web.xml that is generated in ROOT folder :
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5">
</web-app>
If your app includes jersey-spring3 and you don't take steps to disable, it will try to create an ApplicationContext for you (helpful, not). There is a way to switch it off (in a WebApplicationInitializer):
servletContext.setInitParameter("contextConfigLocation", "<NONE>");
Or just use this: https://github.com/dsyer/spring-boot-jersey (include as a dependency).
In my case - I was having the same problem - seeing the Spring splash screen twice - It was because I had 2 classes that extended SpringBootServletInitializer. One was called SpringBootWebApplication and the other ServletInitializer. I just removed the ServletInitializer and it worked OK. Don't know why there were 2 classes - maybe because I got inspired from 2 different examples to assemble what I needed.
In my case the culprit was using Spring Boot 1.3.0.M4, along with Jersey 2.21. When I downgraded Spring Boot to 1.2.6.RELEASE the issue is gone.
The only thing I had to do was to explicitly override the following properties, as I needed spring 4.2.0 for Hibernate 5 support, and jackson 2.6.2 for JSR310 (java8 java.time) support:
<spring.version>4.2.0.RELEASE</spring.version>
<jackson.version>2.6.2</jackson.version>
EDIT: As of spring-boot 1.3.0.RELEASE, this bug still exists. See github
My main problem was my spring context was being loaded twice. As I printed every class's class loader I found that my Application was running twice. (i.e. when I debug in intellij after pressing F9 I was again landing up on same line i.e.
ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigAssignServer.class, args);
My problem was in pom.xml. I removed below dependency from my pom and it worked.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
Please check for your dependencies. Hope it will help someone. Enjoy coding :)
I had the same issue
I have src>main>webapp>WEB-INF>web.xml has an entity to saying
<listener>
<listener-class>org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener</listener-class>
</listener>
This is loading my context second time.
Comment it out and it will load only once.
I'm using Spring Boot 2.5.5 and experiencing the same issue but without error (WebApplicationContext) is being loaded twice along with scheduler calls are triggered as well too.
After debugging my application & Server(Tomcat v9.0.53) settings, I, myself able to solve the issue by deleting the "ServletInitializer.java" class which comes part of Spring initialiser project.
Now, all the issues resolved like schedulers are called once on predefined time along with the context loading.
Hope this resolves the issue.
Seems that "extends SpringBootServletInitializer" not work well with #SpringBootApplication in tomcat but when run with maven no duplicated beans is initialized so removing "extends SpringBootServletInitializer" from application main class solve the problem
In the Spring framework, usually for loading something like a global or root context, you club all the bean/resources shared by multiple servlet contexts.
Or loading a specific servlet context. Mvc-dispatcher config file is used to load config file, so you don't need to explicitly define it.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
In your case, seems when you are running as a Java application, auto-detection of Mvc-dispatcher doesn't happen and you are able to execute the code successfully. Whereas when deployed it gets initiated both from root and mvc-dispatcher.
Use empty context: <context-param/>
I don’t see the contents of web.xml here, So I am throwing a quick suggestion from both perspectives.
Please try to delete dependency from the global/root context.
Or in case #EnableAutoConfiuguration is used, get rid of it.
#EnableAutoConfiuguration from the API says "Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need."
#ComponentScan would also instantiate the beans. IT will scan the packages, find and register the beans.
As you are using both these annotations, I guess that is why its loading twice.

Spring WebApplicationInitializer and Jetty 8.x

I am trying to deploy an app in Jetty using Maven:
I have the plugin configured as follows:
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.0.4.v20111024</version>
</plugin>
And I have a WebApplicationContextInitializer, I have cut it down to a simple form for here:
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
// Register and map the main dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("appServlet", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(2);
dispatcher.addMapping("/site/*");
When I run jetty:run from within Spring Tool Suite I cannot access my servlet. The startup logs are:
[INFO] Configuring Jetty for project: Test
[INFO] webAppSourceDirectory C:\Users\Alex\Documents\spring\Test\src\main\webapp does not exist. Defaulting to C:\Users\Alex\Documents\spring\Test\src\main\webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = C:\Users\Alex\Documents\spring\Test\target\classes
[INFO] Context path = /
[INFO] Tmp directory = C:\Users\Alex\Documents\spring\Test\target\tmp
[INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
[INFO] Web overrides = none
[INFO] web.xml file = null
[INFO] Webapp directory = C:\Users\Alex\Documents\spring\Test\src\main\webapp
2012-02-06 21:22:38.048:INFO:oejs.Server:jetty-8.0.4.v20111024
2012-02-06 21:22:38.807:INFO:oejpw.PlusConfiguration:No Transaction manager found - if your webapp requires one, please configure one.
2012-02-06 21:22:41.828:INFO:/:Spring WebApplicationInitializers detected on classpath: [org.test.application.config.TestWebApplicationInitializer#f946f9]
2012-02-06 21:22:41.965:INFO:/:Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Mon Feb 06 21:22:41 GMT 2012]; root of context hierarchy
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#18b24cb: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 235 ms
2012-02-06 21:22:42.344:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/,file:/C:/Users/Alex/Documents/spring/Test/src/main/webapp/},file:/C:/Users/Alex/Documents/spring/Test/src/main/webapp/
2012-02-06 21:22:42.344:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/,file:/C:/Users/Alex/Documents/spring/Test/src/main/webapp/},file:/C:/Users/Alex/Documents/spring/Test/src/main/webapp/
2012-02-06 21:22:42.345:INFO:oejsh.ContextHandler:started o.m.j.p.JettyWebAppContext{/,file:/C:/Users/Alex/Documents/spring/Test/src/main/webapp/},file:/C:/Users/Alex/Documents/spring/Test/src/main/webapp/
2012-02-06 2012-02-06 21:22:42.352:INFO:oejs.AbstractConnector:Started SelectChannelConnector#0.0.0.0:8080 STARTING
[INFO] Started Jetty Server
If then navigate to http://localhost:8080/ I get the default Jetty page with no contexts listed.
I have tried copying webdefaults.xml into my project as described here but this didn't fix the issue. It just removed the default servlet page.
This deploys correctly in Tomcat so I suspect an issue in the maven-jetty-plugin.
Does anyone have any experience in this area?
Edit:
So I can confirm that if I change the Jetty config so that the app is deployed under context /application and then navigate to http://localhost:8080/application/site/ I get a 404.
However, the dispatcher servlet has logged:
No mapping found for HTTP request with URI [/application/site/] in DispatcherServlet with name 'appServlet'
This suggests that there is an issue with my Controller mappings correct?
The startup logs show this mapping is registered:
Mapped "{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.test.application.controller.HomeController.catchAll()
What am I missing?
It seems that the new Jetty plugin is using root "/" as root context of the web application, the old one was as written below:
contextPath Optional. The context path for your webapp. By default,
this is set to the from the project's pom.xml. You can
override it and set it to anything you like here.

No bean named 'cxf' is defined

I am trying to setup a simple restful web application, using tomcat 6.0.32, cxf 2.4.1. Anytime I issue any call, I get back an exception "No bean named 'cxf' is defined", where cxf is my bus.
Looking at the application log, I can see the cxf instance is created, and cached.
================ APP LOG BEGIN======================
910 DEBUG - Creating shared instance of singleton bean 'cxf'
910 DEBUG - Creating instance of bean 'cxf'
1018 DEBUG - Eagerly caching bean 'cxf' to allow for resolving potential circular references
1031 DEBUG - Returning eagerly cached instance of singleton bean 'cxf' that is not fully initialized yet - a consequence of a circular reference
1034 DEBUG - Finished creating instance of bean 'cxf'
1035 DEBUG - Returning cached instance of singleton bean 'org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor'
1035 DEBUG - Returning cached instance of singleton bean 'org.apache.cxf.bus.spring.Jsr250BeanPostProcessor'
1035 DEBUG - Returning cached instance of singleton bean 'org.apache.cxf.bus.spring.BusExtensionPostProcessor'
1035 DEBUG - Creating shared instance of singleton bean 'connection'
1035 DEBUG - Creating instance of bean 'connection'
1035 DEBUG - Eagerly caching bean 'connection' to allow for resolving potential circular references
1052 DEBUG - Finished creating instance of bean 'connection'
1052 DEBUG - Creating shared instance of singleton bean 'connectionService'
1052 DEBUG - Creating instance of bean 'connectionService'
1053 DEBUG - Eagerly caching bean 'connectionService' to allow for resolving potential circular references
1053 DEBUG - Returning cached instance of singleton bean 'connection'
1053 DEBUG - Returning cached instance of singleton bean 'cxf'
1121 DEBUG - Invoking init method 'create' on bean with name 'connectionService'
1356 DEBUG - Finished creating instance of bean 'connectionService'
1384 DEBUG fecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor#45d1c3cd]
1385 DEBUG - Returning cached instance of singleton bean 'lifecycleProcessor'
1387 DEBUG - Returning cached instance of singleton bean 'cxf'
1387 DEBUG - Returning cached instance of singleton bean 'cxf'
1388 DEBUG - Invoking init method 'create' on bean with name 'connectionService'
1391 DEBUG - Finished creating instance of bean 'connectionService'
1391 DEBUG - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor#2c3299f6]
1391 DEBUG - Returning cached instance of singleton bean 'lifecycleProcessor'
1391 DEBUG - Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT]
1391 INFO - Root WebApplicationContext: initialization completed in 1390 ms
================ APP LOG END======================
But when a request comes in, it always fails saying it can't find the bean.
===================== Tomcat (localhost) Log Begin ==================
INFO: Initializing Spring root WebApplicationContext
Jul 14, 2011 8:57:03 AM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'cxf' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1083)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1079)
at org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:58)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:54)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:809)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
at java.lang.Thread.run(Thread.java:662)
===================== Tomcat (localhost) Log End ==================
The only thing I can think of is that the bean is inserted in one context, and is being retrieved from another, but can't validate this or find a way around it. Any help would be greatly appreciated.
From your error log, I assume you use Spring, if so, you will need to add following lines to your Spring Context XML:
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-xml.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
Hope this helps.
If someone needs the Spring Java Based Configuration for solving this problem, there are two options:
You can import the cxf.xml file into your Java Config class with:
#ImportResource({ "classpath:META-INF/cxf/cxf.xml" })
Or you can define the bean programatically in your Java Configuration class with:
#Bean
public SpringBus cxf() {
return new SpringBus();
}
CXF + Spring Java Configuration class example.
In case anybody else gets here and is using mulesoft esb. The problem is also present in this system. To fix the issue, add the following section before the definition of the flows.
<spring:beans>
<spring:import resource="classpath:META-INF/cxf/cxf.xml" />
<spring:import resource="classpath:META-INF/cxf/cxf-extension-xml.xml" />
<spring:import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<spring:bean class="org.apache.cxf.bus.spring.Jsr250BeanPostProcessor" />
<spring:bean id="classname" name="classname" class="some.implemented.interface.path" />
</spring:beans>
Add these dependencies in the pom file:
<dependency>
   <groupId>org.apache.cxf</groupId>
   <artifactId>cxf-rt-rs-extension-search</artifactId>
   <version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.1</version>
</dependency>
Please check these steps in below:
1) lines mentioned in below should be included in your Spring Context XML:
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
2) Web.xml should be configured as below:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:cxf.xml</param-value>
</context-param>
3) Dependencies in below should be added inside your pom.xml:
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-ws-security</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-ws-policy</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-service-description</artifactId>
<version>${cxf.version}</version>
</dependency>
If all this didnt help you to solve your issue, the last step is to check your weblogic configuration, here are the steps you have to check on your weblogic server:
make sure you have define a machine to your server.
you need to specify your server and machine for your deployment as below:
Weblogic app deployment
I hope by checking all these steps your issue get solved.
Cheers

Resources