Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean while loading the context xml in run method - spring

#Configuration
#EnableAutoConfiguration
#ComponentScan
#SpringBootApplication
public class InitService extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run("classpath:abc-server.xml", args);
}
}
++++++++++++++++++++++++++++++++++++++++++
Here i am trying to migrate the Spring MVC project to Spring boot Standalone jar with embedded tomcat. So i tried loading the context xml(abc-server.xml) used in the existing project. When i run/deploy the spring boot jar, the following exception is thrown.
++++++++++++++++++++++++++++++++++++
[2015-05-19 15:12:30,012] ERROR org.springframework.boot.SpringApplication - Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.gogo.asp.server.init.InitService.main(InitService.java:188)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:183)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:156)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
... 13 more

When you call run, you're only providing server-abc.xml as a source for your application's configuration:
SpringApplication.run("classpath:abc-server.xml", args);
That means that InitService is being ignored, including the fact that you've enabled auto-configuration. Without auto-configuration being switched on, Spring Boot will not automatically configure an embedded servlet container for you. You need to provide both InitService and abc-server.xml as configuration for your application.
I would provide InitService.class to SpringApplication.run and use #ImportResource to pull in your old XML configuration:
#SpringBootApplication
#ImportResource("classpath:abc-server.xml")
public class InitService {
public static void main(String[] args) {
SpringApplication.run(InitService.class, args);
}
}
Note that #SpringBootApplication is equivalent to #ComponentScan, #Configuration, and #EnableAutoConfiguration. You can just use #SpringBootApplication and drop the other three annotations as I've done above.

Related

Spring Boot compatibility issues when upgrading to new libraries

I am in the process of upgrading a Spring Boot application to support Micrometer and Actuator monitoring. I have upgraded the Spring libraries to newer versions, and I have refactored the code accordingly (you can see before and after code samples later in in this question). I could run the application successfully before; when I try to do so now, I am getting the following error message:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-08-20 14:14:59.302 ERROR 29703 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:163) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577) ~[spring-context-5.3.9.jar:5.3.9]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:143) [spring-boot-2.5.3.jar:2.5.3]
at com.openbet.realitycheck.Application.main(Application.java:22) [classes/:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:210) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:160) ~[spring-boot-2.5.3.jar:2.5.3]
... 7 common frames omitted
The below screenshot describes the library versions that were previously used:
enter image description here
These are the upgraded libraries that I am using now:
enter image description here
Some before-and-after code samples:
Before:
#SpringApplicationConfiguration(classes = {Application.class, IntegrationTestConfiguration.class})
#WebIntegrationTest("server.port=0")
After:
#SpringBootTest(classes = {Application.class, IntegrationTestConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
Before:
#SpringApplicationConfiguration(classes = UnitTestConfiguration.class)
After:
#SpringBootTest(classes = UnitTestConfiguration.class)
Here is my starter class:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
// Change the default config name to xxxxxxxxxxxx.
new SpringApplicationBuilder(Application.class)
.properties(Collections.singletonMap("spring.config.name", "xxxxxxxxxxxx"))
.run(args);
}
}
When I specify that this is not a Web Application...
#SpringBootApplication
public class Application {
public static void main(String[] args) {
// Change the default config name to xxxxxxxxxxxx.
new SpringApplicationBuilder(Application.class)
.web(WebApplicationType.NONE)
.properties(Collections.singletonMap("spring.config.name", "xxxxxxxxxxxx"))
.run(args);
}
}
...I receive a different set of error messages:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field customerPrefRepository in com.corpname.appname.core.services.CustomerPrefServiceImpl required a bean of type 'com.corpname.appname.core.repositories.CustomerPrefRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.corpname.appname.core.repositories.CustomerPrefRepository' in your configuration.
As this is a web-based application, I don't know of how much use this last bit for information would be.

Spring server doesn't start with actuator dependency

If I add spring boot actuator dependency my server doesn't start. I get the following error:
SEVERE [main] org.apache.catalina.startup.HostConfig.deployDescriptor Error deploying deployment descriptor [tomcat path\conf\Catalina\localhost\test.xml]
java.lang.IllegalStateException: Error starting child
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:720)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:690)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:692)
...
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/agromarket]]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:717)
... 37 more
Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
at rs.navigator.alexandar.sync.WebAppInitializer.onStartup(WebAppInitializer.java:34)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Any ideas why? From my knowledge even if the versions aren't compatible the server should still be able to start.
Edit:
My WebAppInitializer:
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println(("------------------ Sync context initialized and application started ------------------"));
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
// ctx.register(ServletContextListener.class);
// ctx.register(SecurityConfiguration.class);
// ctx.register(SpringFoxConfig.class);
// ctx.register(WebMvcConfigure.class);
// ctx.register(JPAConfiguration.class);
// ctx.setServletContext(servletContext);
// Reconfigure log4j
// ServletContext sctx = ctx.getServletContext();
System.setProperty("logFilename", servletContext.getContextPath().substring(1));
org.apache.logging.log4j.core.LoggerContext sctxLog =
(org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
sctxLog.reconfigure();
//Dispatcher servlet
ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
ctx.close();
}
}
Error stack after adding #EnableAutoConfiguration
If you want benefit from the automatic features of Spring Boot, your #Configuration class must be annotated with #EnableAutoConfiguration.
Since the auto-configuration already creates a DispatcherServlet bound to /, you can safely change your WebAppInitializer class to:
#SpringBootApplication
public class WebAppInitializer extends SpringBootServletInitializer {
}

Wildfly / Infinispan HTTP session replication hits ClassNotFoundException when unmarshalling CGLIB Session Bean

I'm running Wildfly 20.0.1.Final in standalone, two-node cluster. I'm trying to implement HTTP Session sharing between the nodes.
In my Spring web application I have <distributable/> in my web.xml.
My session object is this:
package my.package;
#Component
#Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.INTERFACES)
public class MySessionBean implements Serializable {
// omitted for brevity
}
As you can see, I have ScopedProxyMode.TARGET_CLASS.
When I perform a failover in Wildfly, my HTTP Session can't be restored however, as I hit this warning:
2021-02-22 13:24:18,651 WARN [org.wildfly.clustering.web.infinispan] (default task-1) WFLYCLWEBINF0007:
Failed to activate attributes of session Pd9oI0OBiZSC9we0uXsZdBwkLnadO1l4TUfvoJZf:
org.wildfly.clustering.marshalling.spi.InvalidSerializedFormException:
java.lang.ClassNotFoundException: my.package.MySessionBean$$EnhancerBySpringCGLIB$$9c0fa1df
from [Module "deployment.myDeployment.war" from Service Module Loader]
...
Caused by: java.lang.ClassNotFoundException: my.package.MySessionBean$$EnhancerBySpringCGLIB$$9c0fa1df from [Module "deployment.myDeployment.war" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:255)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at org.jboss.marshalling#2.0.9.Final//org.jboss.marshalling.ModularClassResolver.resolveClass(ModularClassResolver.java:133)
at org.jboss.marshalling.river#2.0.9.Final//org.jboss.marshalling.river.RiverUnmarshaller.doReadClassDescriptor(RiverUnmarshaller.java:1033)
at org.jboss.marshalling.river#2.0.9.Final//org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1366)
at org.jboss.marshalling.river#2.0.9.Final//org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:283)
at org.jboss.marshalling.river#2.0.9.Final//org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:216)
at org.jboss.marshalling#2.0.9.Final//org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:41)
at org.wildfly.clustering.marshalling.spi#20.0.1.Final//org.wildfly.clustering.marshalling.spi.util.MapExternalizer.readObject(MapExternalizer.java:65)
...
Note, that the ClassNotFoundException is complaining because the lack of my.package.MySessionBean$$EnhancerBySpringCGLIB$$9c0fa1df, which is the Spring-enhanced bean of my MySessionBean bean.
Changing to ScopedProxyMode.INTERFACES is not an option.
Can you please point me in the right direction with this?
I managed to fix this by creating a simple POJO, called MySessionDTO, and using that in my session.
So initially I had this (which threw the exception in the question):
request.getSession().setAttribute("mySession", mySessionBean);
...and after I created MySessionDTO (see below), I refactored it into this:
request.getSession().setAttribute("mySession", mySessionBean.getMySessionDTO());
MySessionDTO is a simple POJO:
package my.package;
import java.io.Serializable;
public class MySessionDTO extends MySessionBean implements Serializable {
public MySessionDTO (MySessionBean mySessionBean) {
this.setAttributeX(mySessionBean.getAttributeX());
this.setAttributeY(mySessionBean.getAttributeY());
}
}

Serving static content with spring boot and resteasy

I have integrated resteasy with spring boot for our backend web application. My application.java file looks like below
#ComponentScan(basePackages = "<basepackage>")
#EnableAutoConfiguration
#EnableWebMvc
#ImportResource(value = { "classpath:springmvc-resteasy.xml" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
In order to serve static content from my web application, it was suggested #https://stackoverflow.com/questions/24661289/spring-boot-not-serving-static-content to extend WebMvcAutoConfigurationAdapter. Once I did the same, I got the following exception
java.lang.IllegalStateException: could not find the type for bean named faviconRequestHandler
at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.getBeanClass(SpringBeanProcessor.java:437) ~[resteasy-spring-3.0.8.Final.jar:na]
at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.processBean(SpringBeanProcessor.java:294) ~[resteasy-spring-3.0.8.Final.jar:na]
at org.jboss.resteasy.plugins.spring.SpringBeanProcessor.postProcessBeanFactory(SpringBeanProcessor.java:272) ~[resteasy-spring-3.0.8.Final.jar:na]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265) ~[spring-context-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:170) ~[spring-context-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609) ~[spring-context-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) ~[spring-context-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120) ~[spring-boot-1.1.5.RELEASE.jar:1.1.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691) [spring-boot-1.1.5.RELEASE.jar:1.1.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) [spring-boot-1.1.5.RELEASE.jar:1.1.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952) [spring-boot-1.1.5.RELEASE.jar:1.1.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941) [spring-boot-1.1.5.RELEASE.jar:1.1.5.RELEASE]
at com.xactly.insights.app.Application.main(Application.java:33) [classes/:na]
I package my application as executable jar. Can anyone throw some light on how to avoid the above exception while serving the static content?

Spring Boot 1.0.0-RC4 starts with multiple EmbeddedServletContainerFactory instances

I am looking to override the default EmbeddedServletContainerFactory as documented here in order to set up SSL. The old docs (from RC1 days) said to override the Customizer and that worked great until I upgraded today, changed the implementation to follow the new convention.
#Configuration
public class ContainerConfig {
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
#Override
public void customize(Connector connector) {
connector.setPort(8443);
connector.setSecure(true);
connector.setScheme("https");
connector.setAttribute("keyAlias", "tomcat");
connector.setAttribute("keystorePass", "changeit");
try {
connector.setAttribute("keystoreFile", ResourceUtils.getFile("src/ssl/tomcat.keystore").getAbsolutePath());
} catch (FileNotFoundException e) {
throw new IllegalStateException("Cannot load keystore", e);
}
connector.setAttribute("clientAuth", "false");
connector.setAttribute("sslProtocol", "TLS");
connector.setAttribute("SSLEnabled", true);
}
});
factory.setSessionTimeout(10, TimeUnit.MINUTES);
return factory;
}
The source code in Boot (EmbeddedServletContainerAutoConfiguration) indicates that if it does find my bean, it will not register the default:
#ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
However it appears to register anyhow. Does anybody else have this working? Here is the stack:
Exception in thread "main"
org.springframework.context.ApplicationContextException: Unable to
start embedded container; nested exception is
org.springframework.context.ApplicationContextException: Unable to
start EmbeddedWebApplicationContext due to multiple
EmbeddedServletContainerFactory beans :
servletContainer,tomcatEmbeddedServletContainerFactory at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:135)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:619)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:306)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:880)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:869)
at
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.springframework.context.ApplicationContextException:
Unable to start EmbeddedWebApplicationContext due to multiple
EmbeddedServletContainerFactory beans :
servletContainer,tomcatEmbeddedServletContainerFactory at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)
at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158)
at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:132)
... 12 more
I have created a GitHub repo that mashes up the Tomcat and Websocket samples from the Spring Boot project, and applies this configuration.
This is a (sort of) bug (https://github.com/spring-projects/spring-boot/issues/479). Fixed now. Workaround is to use EmbeddedServletContainerCustomizer instead of EmbeddedServletContainerFactory (like in the docs link in the original question).

Resources