Spring Boot JPA H2 Console not running, application.properties file ignored - gradle

The Spring Boot guide says I can get the H2 console but it's not working for me.
http://localhost:8080/h2/ Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Oct 26 12:31:46 BST 2016
There was an unexpected error (type=Not Found, status=404).
No message available
I created an application.properties file as follows
spring.h2.console.enabled=true
spring.h2.console.path=/h2
My project is based on this
The default path /h2-console doesn't work either.
I found another answer where the problem is solved by adding to Application.java:
#Bean
public ServletRegistrationBean h2servletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(new WebServlet());
registration.addUrlMappings("/h2/*");
return registration;
}
Everything in my application.properties file is ignored. I have tried adding:
spring.datasource.url=jdbc:h2:file:~/portal;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
But the database is still created in memory only.

Check if you set a base path in application.properties.
For example, if you have a setting
server.contextPath=/api
You access the h2 Console under
http://localhost:8080/api/h2-console
Obvious, but that was it for me

Another possible cause for this problem, is if you're using spring security.
In that case, you may want to add a specific permission to the h2-console URL you defined.
For example, for the default h2-console configuration (without a spring.h2.console.path property), you will add this inside your WebSecurityConfigurerAdapter extending class:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated();
http.headers().frameOptions().sameOrigin();
}
Please also note that line at the end - http.headers().frameOptions().sameOrigin();.
It's needed to prevent a Whitelable page error when logging in to the console.
This is described also here.

Your current location src\main\java\h‌​ello\application.pro‌​perties is the culprit. For 2 reasons.
Non java resources in src\main\java are ignored
only application.properties in the root or config directory or taken into account (by default). (See the reference guide).
The fix is to simply move your application.properties to src\main\resources.

In my case, I just had to remove the tag <scope>runtime</scope> from the h2 dependency as explained in here.

a / is missing before spring.h2.console.path it have to look like :
spring.h2.console.path=/h2
also when you indicate spring.h2.console.path /h2-console is no more available
Regards

I tried h2-console while building my microservice project and fell into the same issue "Whitelabel error page".
I haven't added any security in my project for now but I found the problem for me is solved by removing spring.h2.console.enabled= true from application.properties and adding dependency dev-tools. for me not adding dev-tools also caused the problem so try to add this dependency as well. while of course, you will add h2, actuator, web dependencies.

Try the below in application.properties
spring.h2.console.enabled: true

try to add to application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
//then
create class SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll().and()
.authorizeRequests().antMatchers("/h2-console/**").permitAll();
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
}

For me scope=test was the issue as I carelessly copied from https://mvnrepository.com/artifact/com.h2database/h2/1.4.200
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>
And replaced it with
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>runtime</scope>
</dependency>
After this, it should work with default configurations.
I am not using spring security, but you might need to make certain changes accordingly. Please check above answers for that https://stackoverflow.com/a/59729714/7359806

First, make sure to have these dependencies:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Then add these to your application.properties:
##spring.main.web-application-type=none make sure it's commented
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
##server.port=9999 make sure you use default port (8080). In other words, don't specify a server.port

For me - a computer restart fixed it.
Not sure why this would be the cause but perhaps a port was occupied, or the h2 related files were not deployed correctly
make sure you that when the springBoot application is launched, you can see the log lines for Hibernate and H2 are present:
2017-04-22 14:41:03.195 INFO 912 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-04-22 14:41:03.197 INFO 912 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-04-22 14:41:03.199 INFO 912 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-04-22 14:41:03.278 INFO 912 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-04-22 14:41:03.469 INFO 912 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-04-22 14:41:03.935 INFO 912 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-04-22 14:41:03.945 INFO 912 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete

For this problem, i just add the default string at my application.properties and works.
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
Maybe the spring boot dont set this for some reason.

Remove <scope>test</scope> from h2 dependency in pom.xml works in my case.
Don't forget to reinstall and build again after your modification.
<!-- H2 database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
<!-- <scope>test</scope> -->
</dependency>

I used compile otherwise testCompile in the Gradle declaration and was worked fine for me.
Example:
compile group: 'com.h2database', name: 'h2', version: '1.4.200'

If you are having troubles with the program ignoring the application.properties and you are using Eclipse, do the following:
Move the application.properties into the src/main/resources folder, right click on it and click "build path" -> "Add to build path"

Make sure to use> spring.datasource.url=jdbc:h2:mem:testdb as this db is required for h2

I found the same case using Eclipse 4.26.0
Did some of above method and not work. Until in one forum, someone suggest us to add devtools dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
I hope it works for you.

Related

Spring Eureka asks for username password authentication

Using generated security password: f9268f9c-f2e6-4e53-a751-632a7005b807
2020-03-03 13:07:44.539 INFO 4824 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#2a92f8c3, org.springframework.security.web.context.SecurityContextPersistenceFilter#412324cd, org.springframework.security.web.header.HeaderWriterFilter#7cf2dd91, org.springframework.security.web.csrf.CsrfFilter#565adf96, org.springframework.security.web.authentication.logout.LogoutFilter#5b3457db, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#b1041fc, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#5e842f37, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#3e06198f, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#574d3e0c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#2b5beb1d, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#4d02763e, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#b273c65, org.springframework.security.web.session.SessionManagementFilter#1f6d3131, org.springframework.security.web.access.ExceptionTranslationFilter#1bf860da, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#11538685]
2020-03-03 13:07:44.612 WARN 4824 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : Unable to start LiveReload server
I didn't include spring security dependencies in POM file, but I'm seeing these lines in my console. Browser prompts for user name and password. How can I fix this?
I don't think so u should be verify or dependency in POM
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
Solved! Eureka server has username password authentication by default. Default username is user, and the password will be generated in the console!
This can be set in application.yml (by profile).
spring:
security:
user:
name: <your user>
password: <your password>

Problem with Google Cloud Pub/Sub API and Spring boot application

I write spring boot application for subscribing Google cloud Pub/Sub topic for this I use Google's tutorial, but when I run application I have get this error
2019-02-02 18:03:10.248 INFO 15080 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-02-02 18:03:10.271 INFO 15080 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-02-02 18:03:10.610 ERROR 15080 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of method messageChannelAdapter in tech.garoon.cloud.CloudApplication required a bean of type 'org.springframework.cloud.gcp.pubsub.core.PubSubTemplate' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.cloud.gcp.pubsub.core.PubSubTemplate' in your configuration.
Process finished with exit code 1
How Can I solve this problem?
GcpPubSubAutoConfiguration provides autoconfiguration feature of creating necessary beans including PubSubTemplate. In your case, somethng is missed, Kindly ensure that dependencies are in place or recreate following bean to make it work.
#Bean
public PubSubTemplate pubSubTemplate(PubSubPublisherTemplate pubSubPublisherTemplate,
PubSubSubscriberTemplate pubSubSubscriberTemplate) {
return new PubSubTemplate(pubSubPublisherTemplate, pubSubSubscriberTemplate);
}
Additionally, make sure GcpContextAutoConfiguration is created based on below properties in application.properties.
spring.cloud.gcp.credentials.location=${gcp_credentials}
starter dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gcp-starter-pubsub</artifactId>
</dependency>
Solution
I added this dependency
implementation 'org.springframework.cloud:spring-cloud-gcp-autoconfigure:1.1.0.RELEASE'
My dependencies
dependencies {
implementation 'org.springframework.cloud:spring-cloud-gcp-pubsub:1.1.0.RELEASE'
implementation 'org.springframework.cloud:spring-cloud-gcp-autoconfigure:1.1.0.RELEASE'
implementation "org.springframework.boot:spring-boot-starter-web:2.1.2.RELEASE"
implementation 'org.springframework.integration:spring-integration-core:5.1.2.RELEASE'
}
if using external configuration class that is registering your channels, message handlers etc, make sure to annotate the configuration class with #Import({GcpPubSubAutoConfiguration.class})
#Configuration
#Import({GcpPubSubAutoConfiguration.class})
public class PubSubConfig{
}
I ran into this issue with these versions of spring-boot and spring-cloud-gcp-starter-pub:
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gcp-starter-pubsub</artifactId>
<version>1.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.2.8.RELEASE</version>
</dependency>
and in my application.properties I had
spring.cloud.gcp.pubsub.enabled=false for local development.
I removed spring.cloud.gcp.pubsub.enabled=false and it worked. Although now it creates a connection to the pubsub gcp topic, so for local development, you will need to comment out publishing, to avoid sending messages.

OpenTracing not activating for Sleuth-Zipkin in Spring Boot App

Spring Doc says
Spring Cloud Sleuth is compatible with OpenTracing. If you have OpenTracing on the classpath, we automatically register the OpenTracing Tracer bean. If you wish to disable this, set spring.sleuth.opentracing.enabled to false
I have the below dependency in my POM.
<dependency>
<groupId>io.opentracing.contrib</groupId>
<artifactId>opentracing-spring-cloud-starter</artifactId>
<version>${version.opentracing.spring}</version>
</dependency>
But, I get the following print out it the logs when I try to print the trace and span information : tracer: NoopTracer
2018-11-19 12:12:03.938 [{X-B3-SpanId=4cd8eed6fe759bd1, X-B3-TraceId=5bf25b3bd0714ae54cd8eed6fe759bd1, X-Span-Export=true, spanExportable=true, spanId=4cd8eed6fe759bd1, traceId=5bf25b3bd0714ae54cd8eed6fe759bd1}] DEBUG ahallim-1ef960 --- [nio-7070-exec-1] a.h.w.RestaurantController : tracer: NoopTracer
2018-11-19 12:12:03.939 [{X-B3-SpanId=4cd8eed6fe759bd1, X-B3-TraceId=5bf25b3bd0714ae54cd8eed6fe759bd1, X-Span-Export=true, spanExportable=true, spanId=4cd8eed6fe759bd1, traceId=5bf25b3bd0714ae54cd8eed6fe759bd1}] INFO ahallim-1ef960 --- [nio-7070-exec-1] a.h.w.RestaurantController : active span: null
Why am I getting a NopTracer? Why isn't Brave being registered automatically as promised? Am I doing something wrong?
I am using
Finchley.SR2
I was using Finchley.SR2 train of releases. Once I upgraded to the latest Spring Boot and Spring Cloud versions, the issue fixed itself.
I removed the opentracing-spring-cloud-starter dependency and am now just using
<dependency>
<groupId>io.opentracing.brave</groupId>
<artifactId>brave-opentracing</artifactId>
</dependency>

RestController test fails with h2 database

I am trying to run a test to my RestController in my Spring boot application with h2 database.
Here is some code:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
#ActiveProfiles("test")
public class E2E_EconomicOperatorAPIControllerTest {
#Autowired
private TestRestTemplate restTemplate;
#Test public void test_newEconomicOperator() {
//staff
}
}
But when I run it, i get this error:
2018-04-03 12:16:57.084 WARN 14332 --- [ Thread-7] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-196]
And here is my properties file:
spring.datasource.url=jdbc:h2:mem:testdb;MODE=Oracle;DB_CLOSE_DELAY=-1
logging.level.org.gso.admin=DEBUG
logging.level.gso.gd.client=INFO
logging.level.org.springframework.web.client=WARN
logging.level.org.springframework=WARN
logging.level.org.thymeleaf=WARN
logging.level.root=WARN
Actually, you shouldn't need to set any property for an embedded h2 database, as boot configures that for you (additionally, I think you should leave out the MODE=Oracle flag). Here's what I did:
Put the following dependendy in your .pom:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
Note the scope. This will load the dependency on your classpath during test (and nothing else). You should then make sure, that you have an application.properties file per environment, where you set the database wehnever you need a real one.
As an example from my app:
application-dev.properties: (note: I wanted a real db for dev, so i put in prostgres...)
spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=validate
spring.database.driverClassname=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://192.168.1.100:5432/winecellar
spring.datasource.username=winecellar
spring.datasource.password=winecellar
application-test.properties:
spring.jpa.database=H2
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.database.driverClassname=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.username=sa
spring.datasource.password=
And I have a similar file for production settings (using postgres as well...)
Then, as long as you annotate it as you have done with #ActiveProfiles("test"), you should be fine.

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.

Resources