Spring Boot without the web server - java

I have a simple Spring Boot application that gets messages from a JMS queue and saves some data to a log file, but does not need a web server. Is there any way of starting Spring Boot without the web server?

if you want to run Spring Boot 1.x without a servlet container, but with one on the classpath (e.g. for tests), use the following, as described in the spring boot documentation:
#Configuration
#EnableAutoConfiguration
public class MyClass {
public static void main(String[] args) throws JAXBException {
SpringApplication app = new SpringApplication(MyClass.class);
app.setWebEnvironment(false); //<<<<<<<<<
ConfigurableApplicationContext ctx = app.run(args);
}
}
also, I just stumbled across this property:
spring.main.web-environment=false

Spring Boot 2.x, 3.x
Application Properties
spring.main.web-application-type=NONE
# REACTIVE, SERVLET
or SpringApplicationBuilder
#SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(MyApplication.class)
.web(WebApplicationType.NONE) // .REACTIVE, .SERVLET
.run(args);
}
}
Where WebApplicationType:
NONE - The application should not run as a web application and should not start an embedded web server.
REACTIVE - The application should run as a reactive web application and should start an embedded reactive web server.
SERVLET - The application should run as a servlet-based web application and should start an embedded servlet web server.

You can create something like this:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(false).run(args);
}
}
And
#Component
public class CommandLiner implements CommandLineRunner {
#Override
public void run(String... args) throws Exception {
// Put your logic here
}
}
The dependency is still there though but not used.

Spring boot will not include embedded tomcat if you don't have Tomcat dependencies on the classpath.
You can view this fact yourself at the class EmbeddedServletContainerAutoConfiguration whose source you can find here.
The meat of the code is the use of the #ConditionalOnClass annotation on the class EmbeddedTomcat
Also, for more information check out this and this guide and this part of the documentation

The simplest solution. in your application.properties file. add the following property as mentioned by a previous answer:
spring.main.web-environment=false
For version 2.0.0 of Spring boot starter, use the following property :
spring.main.web-application-type=none
For documentation on all properties use this link : https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Use this code.
SpringApplication application = new SpringApplication(DemoApplication.class);
application.setWebApplicationType(WebApplicationType.NONE);
application.run(args);

For Spring boot v2.1.3.RELEASE, just add the follow properties into application.propertes:
spring.main.web-application-type=none

If you need web functionality in your application (like org.springframework.web.client.RestTemplate for REST calls) but you don't want to start a TOMCAT server, just exclude it in the POM:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>

Through program :
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(YourApplicationMain.class)
.web(WebApplicationType.NONE)
.run(args);
Through application.properties file :
spring.main.web-environment=false
Through application.yml file :
spring:
main:
web-environment:false

Spring boot has many starters, some starters have an embedded web server, some don't. The following have the embedded web server:
spring-boot-starter-web
spring-boot-starter-data-jpa
spring-boot-starter-jetty
spring-boot-starter-tomcat
spring-boot-starter-jdbc
spring-boot-starter-data-rest
...
Pick the one that meets your requirements and that does not have server support.
I only need to make restful json api request in my spring application, so the starter I need is
spring-boot-starter-json
which provide RestTemplate and jackson for me to use.

You can use the spring-boot-starter dependency. This will not have the web stuff.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

If you want to use one of the "Getting Started" templates from spring.io site, but you don't need any of the servlet-related stuff that comes with the "default" ("gs/spring-boot") template, you can try the scheduling-tasks template (whose pom* contains spring-boot-starter etc) instead:
https://spring.io/guides/gs/scheduling-tasks/
That gives you Spring Boot, and the app runs as a standalone (no servlets or spring-webmvc etc are included in the pom). Which is what you wanted (though you may need to add some JMS-specific stuff, as someone else points out already).
[* I'm using Maven, but assume that a Gradle build will work similarly].

Remove folowing dependancy on your pom file will work for me
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

For Kotling here is what I used lately:
// src/main/com.blabla/ShellApplication.kt
/**
* Main entry point for the shell application.
*/
#SpringBootApplication
public class ShellApplication : CommandLineRunner {
companion object {
#JvmStatic
fun main(args: Array<String>) {
val application = SpringApplication(ShellApplication::class.java)
application.webApplicationType = WebApplicationType.NONE
application.run(*args);
}
}
override fun run(vararg args: String?) {}
}
// src/main/com.blabla/command/CustomCommand.kt
#ShellComponent
public class CustomCommand {
private val logger = KotlinLogging.logger {}
#ShellMethod("Import, create and update data from CSV")
public fun importCsv(#ShellOption() file: String) {
logger.info("Hi")
}
}
And everything boot normally ending up with a shell with my custom command available.

In Spring boot, Spring Web dependency provides an embedded Apache Tomcat web server. If you remove spring-boot-starter-web dependency in the pom.xml then it doesn't provide an embedded web server.
remove the following dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

From my experience on spring boot > 2.5 ,
if you plan to build the application as a jar file, in my opinion the solution of spring.main.web-application-type=NONE should not be widely accepted and used, since it has only a limited scope of benefits.
For asking to have spring boot without the web server, it means that you have from Spring either the dependency spring-boot-starter-web to build a spring web application or the dependency spring-boot-starter-jersey to build a jax-rs web application. Those dependencies pack inside the spring-boot-starter-tomcat which will then bring the dependency of tomcat-embed-core which is the actual tomcat server. This library is packed automatically inside and is of size ~3.3 MB. Even if you disable the server with the aforementioned property, you will still deliver your application jar file, containing the tomcat server inside.
So the con of just using the aforementioned property is that the deliverable jar file will be some MB larger in size without any actual need.
So if you want to have spring boot without the web server just don't use the dependencies spring-boot-starter-jersey or spring-boot-starter-web since if you build your application as a jar file there is no reason to have those dependencies and not have an embedded server delivered.
if you plan to build the application as a war file, you should also not use the above property.
In this case you will just need in your .pom the following configurations
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web or (spring-boot-starter-jersey)</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>pick the version that the server that already runs in production supports</version>
<scope>provided</scope>
</dependency>
</dependencies>
Exceptional cases
The property spring.main.web-application-type=NONE should be in my opinion used for some exceptional cases like if we build some web library that needs the above dependencies but is not to be used like a web application, or we have some complex type of testing that needs those libraries although the application does not need any server to run. This type of usages are however rare.

Similar to #nayun oh answer above, but for older versions of Spring, use this code:
SpringApplication application = new SpringApplication(DemoApplication.class);
application.setApplicationContextClass(AnnotationConfigApplicationContext.class);
application.run(args);

Related

Java modules Jigsaw JPMS modularization prevents Spring container from starting rest controller because of org.apache.juli.logging.Log

I am having an issue after switching to Java 11 and adding modules to a Spring Boot application that acts as a REST API. I am not getting any errors when running the application and it shuts down after initialization with exit code 0. The Tomcat embedded server does not start, nor the dispatch server, which would prevent the application from closing and listen for incoming requests.
To me it looks like it does not start the embedded container because the modularization is preventing the Spring Boot Autoconfigure to find some Conditional Beans to initiate the REST server.
There is no error. It acts like if you run the application without a controller, it will shutdown without errors since there is no server to block it. I have listed the beans in the context and the HelloController is there, but like I said I can not find any beans that should exist for a running server, like web.servlet.DispatcherServlet.
I have tried searching for this, but unfortunately the fact that the term module existed long before Java 9 with a different meaning, makes it hard to find any answer. I apologize if somewhere deep in SO this question was already posted.
Even the basic example I can not make it work
Application.java
#SpringBootApplication()
public class SchoolsApplication {
public static void main(String[] args) {
SpringApplication.run(SchoolsApplication.class, args);
}
}
HelloController.java
#RestController
public class HelloController {
#GetMapping("hello")
public String hello(){
return "hello";
}
}
module-info.java
module controllers {
requires spring.boot;
requires spring.boot.autoconfigure;
requires spring.context;
requires spring.beans;
requires spring.web;
requires com.fasterxml.jackson.databind;
opens package.controllers to spring.core;
}
I am using Spring 2.3.4.RELEASE and I am in fact using JDK14, but target is Java 11.
I have tried to play with the required modules (i.e. spring.webmvc, tomcat.embedded.core) or search for the exact Spring beans to include, but with no success.
EDIT
When adding explicitly requires org.apache.tomcat.embed.core; the server starts and crashes with the error
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory]: Factory method 'tomcatServletWebServerFactory' threw exception
...
java.util.ServiceConfigurationError: org.apache.juli.logging.Log: module org.apache.tomcat.embed.core does not declare `uses`
The Tomcat version is 9.0.38
I managed to pinpoint the error to the Tomcat embedded server. The version used by spring-web-starter is tomcat-embed-core:9.0.38 . The issue was fixed in tomcat-embed-core:9.0.39 with
open module org.apache.tomcat.embed.core {
...
uses org.apache.juli.logging.Log;
}
So I resolved this through maven dependency management.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.39</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.39</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

#startup and #postConstruct not called at payara startup

I am developing a JEE application and I want to do some migration when the application starts. Actually, I am using payara-micro with Docker as a server. For an unknown reason, this code is never executed.
Here is my code :
#Singleton
#Startup
public class FlywayMigration {
#PostConstruct
public void startMigration(){
System.out.println("Starting flyway migration");
}
}
I added the javaee-api as dependency in my pom :
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
Here is the content of my Dockerfile :
FROM payara/micro
COPY ./target/mywebapp.war $DEPLOY_DIR
After building and running the docker image, the logs of the application shows that the app started well :
Payara Micro URLs
http://5b258e6a441a:8080/mywebapp
'mywebapp' REST Endpoints
GET /mywebapp/api/hello
GET /mywebapp/api/myresource
Can anyone help me find a solution ?
I finally make it work. The problem is that I was using the bad #Singleton annotation. Instead of using #javax.ejb.Singleton I used to #javax.inject.Singleton.

Springboot integration with RestEasy and deploying to Jboss server

I wanted to integrate Spring boot with RestEasy.
I started using Paypal Springboot starter for the same by referring the link
I have added paypal resteasy dependency as mentioned in the above link.
But while deploying to Jboss server i am getting error below:
Caused by: java.lang.NoClassDefFoundError: org/jboss/resteasy/spi/NotImplementedYetException
at java.lang.Class.getDeclaredConstructors0(Native Method) [rt.jar:1.8.0_131]
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source) [rt.jar:1.8.0_131]
at java.lang.Class.getConstructor0(Unknown Source) [rt.jar:1.8.0_131]
at java.lang.Class.newInstance(Unknown Source) [rt.jar:1.8.0_131]
at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:194)
at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.deploy(ServletContainerInitializerDeploymentProcessor.java:131)
Can someone please suggest me the best way to integrate Springboot with RestEasy?
These seem to be two separate questions here: how to integrate RESTEasy, and how to deploy to JBoss.
RESTEasy: The Paypal starter for RESTEasy that you mentioned has been transferred to a new home. https://github.com/resteasy/resteasy-spring-boot/blob/master/mds/USAGE.md
The latest versions works well. (I don't know what changed since the version you used.)
JBoss:
Converting a self-hosting Spring Boot application to one that runs on JBoss requires a few steps, and it's not clear from your writeup which of those changes you've already made.
1) In your pom.xml, change packaging from jar to war.
2) Also in pom.xml, exclude spring-boot-starter-tomcat from any dependencies that try to bring it in. Typically this is spring-boot-starter-web, but if you are using resteasy-spring-boot-starter you would exclude from that instead.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
3) Change main class and make it extend SpringBootServletInitializer.
4) Also in main override the configure method. (Some articles omit this step- it has to do with making sure your components are scanned correctly so there might be ways to configure a project so it is optional.)
public class NameOfMyMainClass extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(NameOfMyMainClass.class);
}
public static void main(String[] args) {
SpringApplication.run(NameOfMyMainClass.class, args);
}
}
These steps are written up in detail here: https://thepracticaldeveloper.com/2018/08/06/how-to-deploy-a-spring-boot-war-in-wildfly-jboss/
In theory that's all you need. But in practice, I never got it working (Spring Boot 2.0.4, JBoss 7.1.)
First issue: Spring Boot 2 apparently requires JBoss 7. I didn't learn this until after I'd wasted some time with JBoss 6.
Second issue: Even after upgrading the server, my JAX-RS beans never worked. According to the following article, JBoss 7.1.1 does not integrate cleanly and requires some additional workarounds: https://ilya-murzinov.github.io/articles/spring-boot-jboss/
There are articles that claim success, but note they tend to be using Wildfly, not JBoss. (It's also possible JBoss 7.0 didn't have all these problems.) So if you are following one of these articles, make sure they are using versions of Spring Boot and JBoss that you can use.

Spring boot RESTful service as WAR not JAR

I am in the process of creating a Java REST application, using Spring-boot. I have successfully loaded the example here and I have tried to convert the JAR file to the WAR file as presented on the Spring-boot site. I've modified my pom.xml file, adding:
<!-- other pom.xml conf -->
<packaging>war</packaging>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
Then I've modified the Application.java class to initialize the servlet (this is for what Spring-boot uses to replace the web.xml file):
public class Application extends SpringBootServletInitializer {
// public static void main(String[] args) {
// new SpringApplicationBuilder(Application.class).run(args);
// }
#Bean
public ServletRegistrationBean jerseyServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(), "/*");
registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyInitialization.class.getName());
return registration;
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
I got my .WAR file generated, but when I deploy it on Tomcat the services are returning 404. The Tomcat logs aren't showing any errors either.
So I am not sure what it might be the problem. If you have any idea please, do share. Thanks!
Update:
Initially it wasn't working because beside the SpringBootApplication annotation to the Application class I was having other annotations too. Took those out and now Tomcat logs are showing this error.
SEVERE: 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!
I am not sure what other ContextLoader is there.
UpdateToUpdate:
Okay, after updating the jars to the latest version, using the annotation #SpringBootApplication for Application.java class, the application starts but when I am calling one of the services I receive:
java.lang.ClassNotFoundException: org.glassfish.jersey.process.internal.RequestExecutorFactory
A google search said that I should add the jersey-common and jersey-core jars, I did, but it didn't fix it. It looks like the RequestExecutorFactory.class is not packaged in the jersey-common-2.19.jar for some reason.
why do you have so many annotation in your Application class here ?
#SpringBootApplication should be sufficient to enable automatic configuration.
Try removing the others.
And put back the main method.
I think you mixed two configuration tw create a war : pre 3.0 and post 3.0 servlet container (as per the Spring Boot documentation)
EDIT :
I've found this question related to your problem.
Jersey is loading a Spring ApplicationContext. See this line of log : Spring WebApplicationInitializers detected on classpath: [com.jersey.Application#148ac084, org.glassfish.jersey.server.spring.SpringWebApplicationInitializer#7807c6d3]
Would it be possible for you to update your Spring Boot version ?
At least 1.20 so you will be able to use the spring-boot-starter-jersey. It will be a lot more easier to integrate Spring and Jersey.
You can find an example here (Spring Boot official examples).
Or you have to exclude the org.glassfish.jersey.server.spring.SpringWebApplicationInitializer of initializers

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

I am totally new to Spring and started to do the official guides from this site:
https://spring.io/guides
I'd like to do this guide:
https://spring.io/guides/gs/scheduling-tasks/
I get the following Exception:
2014-02-14 16:25:21.614 INFO 9032 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerByCGLIB$$5b48d763] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-14 16:25:21.638 INFO 9032 --- [ main] .c.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/work/Spring/SpringTutorial/target/classes/, file:/C:/work/apache-maven-3.0.3/repo/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter/1.0.0.RC1/spring-boot-starter-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot/1.0.0.RC1/spring-boot-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-autoconfigure/1.0.0.RC1/spring-boot-autoconfigure-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-logging/1.0.0.RC1/spring-boot-starter-logging-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jul-to-slf4j/1.7.5/jul-to-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/log4j-over-slf4j/1.7.5/log4j-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-web/1.0.0.RC1/spring-boot-starter-web-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-tomcat/1.0.0.RC1/spring-boot-starter-tomcat-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-core/7.0.47/tomcat-embed-core-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.47/tomcat-embed-logging-juli-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-webmvc/4.0.0.RELEASE/spring-webmvc-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-expression/4.0.0.RELEASE/spring-expression-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-databind/2.3.1/jackson-databind-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-annotations/2.3.0/jackson-annotations-2.3.0.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-core/2.3.1/jackson-core-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/commons-lang/commons-lang/2.2/commons-lang-2.2.jar]
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 missing EmbeddedServletContainerFactory bean.
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at hu.kumite.Application.main(Application.java:17)
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:190)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
... 7 more
The application starter class is this:
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(ScheduledTasks.class, args);
}
}
As you can see, the main method contains a commented line. I've already done a tutorial, namely this one: https://spring.io/guides/gs/consuming-rest/
It's up and running. But I can't run the ScheduledTasks app, which is the following:
#EnableScheduling
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
#Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("The time is now " + dateFormat.format(new Date()));
}
}
I use Eclipse and run the Application.java's main as an Application.
Could someone please help me?
The scheduling guide isn't a web app so you probably have some mouldy stuff in your pom.xml from the REST guide? If you follow the instructions closely it should work. Another potential issue with the code you posted above is that your #EnableAutoConfiguration class is not used in the context, only as a main method (which may not be a problem for the scheduling guide but it probably is for a bunch of others).
A scan of the #SpringBootApplication show that it includes the following annotations:
#Configuration
#ComponentScan
#EnableAutoConfiguration
So you could do this too:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(ScheduledTasks.class, args);
}
}
use this one in your pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
or this one :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
I had multiple application classes in one Spring Boot project which had the web started included and wanted to avoid it configuring a web environment for one of them so I manually configured it as below:
#SpringBootApplication
public class Application
{
public static void main(String[] args)
{
new SpringApplicationBuilder(Application.class)
.web(false)
.run(args);
}
}
UPDATE for Spring Boot 2 and above:
#SpringBootApplication
public class Application
{
public static void main(String[] args)
{
new SpringApplicationBuilder(Application.class)
.web(WebApplicationType.NONE)
.run(args);
}
}
Try this
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(ScheduledTasks.class, args);
}
}
The error suggests that the application you are trying to run cannot instantiate an instance of apache tomcat. Make sure you are running the application with tomcat.
if after checking all your dependencies you experience the same problem, try to add the following in your configuration class
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory =
new TomcatEmbeddedServletContainerFactory();
return factory;
}
If you are using an external instance of tomcat (especially for intellij), the problem could be that the IDE is trying to start the embedded tomcat. In this case, remove the following from your pom.xml then configure the external tomcat using the 'Edit Configurations' wizard.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
Add
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
if you experience this exception while using intellij and you are trying to start the application with the run button. Try starting the application from the command line instead. E.g. ensure that you are in the correct directory (directory with your pom file) assuming this is a springboot application run mvn spring-boot:run this did the trick for me.
Additionally I have also seen this error occur when your spring application depends on another application. In this case I had to start the other application first then run.
Adding the annotation #SpringBootApplication Before the starter class fixed this problem for me (so in essence, this error message can mean "you don't have a #SpringBootApplication marked class anywhere, you need at least one)
#SpringBootApplication
public class AppStarter {
public static void main(String[] args) {
SpringApplication.run(AppStarter.class, args);
}
}
I've had similar problems when the main method is on a different class than that passed to SpringApplcation.run()
So the solution would be to use the line you've commented out:
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
If you package it as a single jar and it's non web app try to load app context as below.
#SpringBootApplication
ApplicationContext ctx = new AnnotationConfigApplicationContext(Main.class);
Or use below plugin to package as a single jar
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
you can specify the external configs by using below command to run
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
/http://docs.spring.io/spring-boot/docs/current/reference/htmlboot-features-external-config.html#boot-features-external-config-application-property-files
Note that if you are passing the properties as arguments then don't include #PropertySource("classpath:test.properties") it will override the parameters
If you run it successfully using command line gradle bootRun, while packaging it with command line gradle jar to jar file in order to run it with command line java -jar build/libs/demo.jar, unfortunately, it failed with Exception: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean, in this case, you need to use task bootRepackage of gradle plugin spring-boot to generate special runnable jar.
setup 1
$ gradle clean bootRepackage
setup 2
$ java -jar build/libs/demo.jar
A SpringApplication will attempt to create the right type of ApplicationContext on your behalf. By default, an AnnotationConfigApplicationContext or AnnotationConfigEmbeddedWebApplicationContext will be used, depending on whether you are developing a web application or not.
The algorithm used to determine a ‘web environment’ is fairly simplistic (based on the presence of a few classes). You can use setWebEnvironment(boolean webEnvironment) if you need to override the default.
It is also possible to take complete control of the ApplicationContext type that will be used by calling setApplicationContextClass(…​).
[Tip]
It is often desirable to call setWebEnvironment(false) when using SpringApplication within a JUnit test.
Adding the spring boot starter dependency fixed my error.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
This is required if you want to start the tomcat as an embeded server.
check your pom.xml is exists
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
I've had a problem like this;For lack this dependency
In my case we added the #Profile annotation newly in order to ignore the TestApplication class in production mode and the Application class in test mode.
Unfortunately, we forgot to add the following line into the application.properties files:
spring.profiles.active=test
or
spring.profiles.active=production
Without these config no profile was loaded which caused the not-so-much saying Spring Error.
This should be caused by dependency issue, in general, you need to check the dependency.
The problem it's in this class:
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
//SpringApplication.run(Application.class, args);
SpringApplication.run(ScheduledTasks.class, args);
}
}
The correct way to launch your application is:
#SpringBootApplication
#EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Clear repository is one possible solution.
Windows -> delete all subfolders in the maven repository:
C:\Users\YourUserName.m2\repository
I have stuck with same problem. As I didn't define Main.class and the following annotations in Spring-Boot using Maven:
#SpringBootApplication
public class Main {
public static void main(String args[]){
SpringApplication.run(Main.class, args);
}
}
Probably you missing #SpringBootApplication in your spring boot starter class.
#SpringBootApplication
public class LoginSecurityAppApplication {
public static void main(String[] args) {
SpringApplication.run(LoginSecurityAppApplication.class, args);
}
}
Problem is exclusion of starter tomcat, I tried exclude it and use vert.x, so when I integrate wit Spring Admin, started problems
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
I had this Exception in the following situation.
in my POM was properties:
<properties>
<java.version>1.8</java.version>
<!-- The main class to start by executing java -jar -->
<start-class>com.scmaer.java.microservice.Application</start-class>
<cxf.version>3.1.5</cxf.version>
<olingo.version>2.0.10</olingo.version>
<spring.boot.version>1.4.7.RELEASE</spring.boot.version>
<spring.boot.plugin.version>1.5.8.RELEASE</spring.boot.plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<skipTests>false</skipTests>
</properties>
and the name and path of my application class ("start-class") was wrong.
I had a similar issue and the problem was a broken maven repo jar file. In my case, the tomcat-embed-core jar file was broken. So I removed it from the maven repo and refreshed it to download again.
In my case it happen after excluding the resource folder from the pom using the following code.
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>*/*.properties</exclude>
</excludes>
</resource>
</resources>
Commenting this code started my code.
An other cause of this problem is corruption of maven repository jars so you can use the following command to solve the problem :
mvn dependency:purge-local-repository
I am using gradle, met seem issue when I have a commandLineRunner consumes kafka topics and a health check endpoint for receiving incoming hooks. I spent 12 hours to figure out, finally found that I used mybatis-spring-boot-starter with spring-boot-starter-web, and they have some conflicts. Latter I directly introduced mybatis-spring, mybatis and spring-jdbc rather than the mybatis-spring-boot-starter, and the program worked well.
hope this helps
In my case, spring configurations were not loaded as expected. On running from cmd using below command, it worked:
start java -Xms512m -Xmx1024m <and the usual parameters as needed, like PrintGC etc> -Dspring.config.location=<propertiesfiles> -jar <jar>

Categories

Resources