Using Spring Security with a standalone Tomcat doing authentication - spring

I want Tomcat (or rather the admin) to handle the user management.
In Spring I just want to secure some endpoints (index.html and two RESTful controllers) and bind it to either a user or, even better, a group/role.
I want to avoid using xml config inside Spring and use just classes and annotations.
Xml config in tomcat is ok :-)
Booting up spring I see a log entry
2014-06-04 11:37:31.676 INFO 27296 --- [on(2)-127.0.0.1] b.a.s.AuthenticationManagerConfiguration :
Using default password for application endpoints: 543fbdb8-c5d0-4b1b-b7ce-cd6fd008520a
2014-06-04 11:37:31.775 INFO 27296 --- [on(2)-127.0.0.1] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#5867ecdd, ...
...
2014-06-04 11:37:31.794 INFO 27296 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
...
2014-06-04 11:37:31.907 INFO 27296 --- [on(2)-127.0.0.1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/login] onto handler of type [class org.springframework.web.servlet.mvc.ParameterizableViewController]
Trying to call upon the secured route I get a login form, yet using the information from the tomcat-users.xml I get an error Invalid username and password..
So what am I missing?
Setup
I have
vanilla Apache Tomcat 8.0.8
a modified conf/tomcat-users.xml
a modified conf/server.xml
a cloned deployable version of the Securing Spring Web Guide in my local branch and in this folder (intellij module), see github repo
Configuration
Spring
See the WebSecurityConfig class.
tomcat-users.xml
<!-- ... --->
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<role rolename="ROLE_stakeholder"/>
<user username="stakeholder" password="Foobarbaz" roles="ROLE_stakeholder,manager-gui,manager-script,manager-jmx,manager-status"/>
<!-- ... --->
server.xml
<!-- ... --->
<Engine name="Catalina" defaultHost="localhost">
<!-- ... --->
<Realm className="org.apache.catalina.realm.MemoryRealm" />
</Engine>

Related

Spring cloud config server git connection issues

I see issues in the Spring cloud config server (Springboot) logs when connecting to the repo where configs are stored. I'm not sure if it's unable to clone because of credentials or something else (git-upload-pack not permitted). Any pointers to this would be great.
2021-10-06 22:52:51.763 INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-10-06 22:52:51.764 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-10-06 22:52:51.765 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2021-10-06 22:52:54.769 WARN 1 --- [nio-8080-exec-1] .c.s.e.MultipleJGitEnvironmentRepository : Error occured cloning to base directory.
org.eclipse.jgit.api.errors.TransportException: https://github.asdf.asdf.asdf.com/asdfad/sdasdf: git-upload-pack not permitted on 'https://github.asdf.asdf.adsf.com/sdfdf/asdfsad-configs/'
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:254) ~[org.eclipse.jgit-5.1.3.201810200350-r.jar!/:5.1.3.201810200350-r]
at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:306) ~[org.eclipse.jgit-5.1.3.201810200350-r.jar!/:5.1.3.201810200350-r]
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:200) ~[org.eclipse.jgit-5.1.3.201810200350-r.jar!/:5.1.3.201810200350-r]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.cloneToBasedir(JGitEnvironmentRepository.java:612) [spring-cloud-config-server-3.0.4.jar!/:3.0.4]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.copyRepository(JGitEnvironmentRepository.java:587) [spring-cloud-config-server-3.0.4.jar!/:3.0.4]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.createGitClient(JGitEnvironmentRepository.java:570) [spring-cloud-config-server-3.0.4.jar!/:3.0.4]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.refresh(JGitEnvironmentRepository.java:267) [spring-cloud-config-server-3.0.4.jar!/:3.0.4]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.getLocations(JGitEnvironmentRepository.java:245) [spring-cloud-config-server-3.0.4.jar!/:3.0.4]
at org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository.getLocations(MultipleJGitEnvironmentRepository.java:139) [spring-cloud-config-server-3.0.4.jar!/:3.0.4]
The Spring boot app.properties for the config server app looks like this -
spring.cloud.config.server.git.uri=https://github.sdf.sdasdf.asdf.com/asdf/asdf-configs
spring.cloud.config.server.git.username=github-token
spring.cloud.config.server.git.password={github_token}
The endpoint returns the response below:
{"status":"DOWN","components":{"clientConfigServer":{"status":"UNKNOWN","details":{"error":"no property sources located"}},"configServer":{"status":"DOWN","details":{"repository":{"application":"app","profiles":"default"},"error":"org.springframework.cloud.config.server.environment.NoSuchRepositoryException: Cannot clone or checkout repository: https://github-token#github.sdf.sdf.dsfs.com/sdf/sdfsd-configs"}},"discoveryComposite":{"description":"Discovery Client not initialized","status":"UNKNOWN","components":{"discoveryClient":{"description":"Discovery Client not initialized","status":"UNKNOWN"}}},"diskSpace":{"status":"UP","details":{"total":103880232960,"free":24558080000,"threshold":10485760,"exists":true}},"livenessState":{"status":"UP"},"ping":{"status":"UP"},"readinessState":{"status":"UP"},"refreshScope":{"status":"UP"}},"groups":["liveness","readiness"]}
Github token needs to be passed as username which I was configuring against the password property for the spring boot app. The password property needs to be left empty and the Github-token needs to be assigned to the username like below-
spring.cloud.config.server.git.username=asdfasdxxxxxxxyssssysysyssysy
spring.cloud.config.server.git.password=
Token authentication requirements are necesary for Git operations, see this link for more info.:
https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/
Try to add .git in the end of the URI in app.properties
spring.cloud.config.server.git.uri=https://github.sdf.sdasdf.asdf.com/asdf/asdf-configs.git

Spring Framework: mvc:resources does not work

In my Spring Web Application project I've already configured an mvc:resources tag in order to exclude CSS, JS, images ... from DispatcherServlet mapping
Now I need to exclude also a foobar.txt and is placed under /webapp directory like the other static resources but ... It doesn't work.
Here my code snippet
<mvc:resources mapping="/assets/**" location="/assets/" />
<mvc:resources mapping="/foobar.txt" location="/foobar.txt" />
my folder structure is:
/webapp
/webapp/assets
/webapp/foobar.txt
/webapp/...
It's seems like the the first mvc:resources tag (assets) works but the second one (version.txt) doesn't.
I get a 404 page.
These are the difference in console log.
2018-07-12 13:58:25,093 DEBUG [http-nio-8080-exec-6] (DispatcherServlet.java:845) - DispatcherServlet with name 'dispatcher' processing GET request for [/mscbackend/foobar.txt]
2018-07-12 13:58:25,093 DEBUG [http-nio-8080-exec-6] (AbstractHandlerMethodMapping.java:297) - Looking up handler method for path /foobar.txt
2018-07-12 13:58:25,096 DEBUG [http-nio-8080-exec-6] (AbstractHandlerMethodMapping.java:305) - Did not find handler method for [/foobar.txt]
2018-07-12 13:58:25,097 DEBUG [http-nio-8080-exec-6] (AbstractUrlHandlerMapping.java:123) - Mapping [/foobar.txt] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/foobar.txt]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#66894a78]]] and 1 interceptor
2018-07-12 14:08:27,165 DEBUG [http-nio-8080-exec-7] (DispatcherServlet.java:845) - DispatcherServlet with name 'dispatcher' processing GET request for [/mscbackend/assets/css/style.css]
2018-07-12 14:08:27,165 DEBUG [http-nio-8080-exec-7] (AbstractHandlerMethodMapping.java:297) - Looking up handler method for path /assets/css/style.css
2018-07-12 14:08:27,169 DEBUG [http-nio-8080-exec-7] (AbstractHandlerMethodMapping.java:305) - Did not find handler method for [/assets/css/style.css]
2018-07-12 14:08:27,169 DEBUG [http-nio-8080-exec-7] (AbstractUrlHandlerMapping.java:168) - Matching patterns for request [/assets/css/style.css] are [/assets/**]
The weird thing is that in another similar project same configuration works without problems.
Thanks in advance for your support.
Try below configuration.
<mvc:resources location="/", mapping="/resources/**"/>
OR if you want to give classpath for a particular location use below.
<mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>
Try this configuration.
<mvc:resources mapping="/resources/**" location="/resources/" />
I don't why, but sometimes it works. you can give a try.

Spring Boot and Axis2 client runtime issue with Rampart

I am trying to use Axis 2 client to work with a soap based web service. I use Rampart 1.7.1 for WSO Authentication. After I created the stub code using axis2tools I installed the jar files into maven repository and use them as dependency in my pom.xml file. Also I use spring boot for the rest of application which I use the generated libraries as soap client api.
Everything is good in dev environment I can work with web service. And also when I use
mvn spring-boot:run
it works fine and webservice communication is good from UI to Webservice and back(end to end).
when I use
java -jar target/fatjar.jar
When I send request to web service I receive the following error at console:
2017-11-17 16:00:35.140 WARN 31114 --- [nio-8080-exec-2] o.a.axis2.deployment.AxisConfigBuilder : Unable to instantiate deployer org.apache.axis2.deployment.ServiceDeployer; see debug logs for more details
2017-11-17 16:00:35.161 INFO 31114 --- [nio-8080-exec-2] o.a.axis2.deployment.DeploymentEngine : No services directory was found under /home/mehdi/Workspace/EclipseWS/src/main/resources/axis.
2017-11-17 16:00:35.179 INFO 31114 --- [nio-8080-exec-2] o.a.axis2.deployment.ModuleDeployer : Deploying module: rampart-1.7.1 - file:/home/mehdi/Workspace/EclipseWS/src/main/resources/axis/modules/rampart-1.7.1.mar
2017-11-17 16:00:35.185 ERROR 31114 --- [nio-8080-exec-2] o.a.axis2.deployment.ModuleDeployer : The rampart-1.7.1.jar module, which is not valid, caused The /home/mehdi/Workspace/EclipseWS/target/cybersourceClient-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/rampart-1.7.1.jar file cannot be found.
org.apache.axis2.AxisFault: The /home/mehdi/Workspace/EclipseWS/target/cybersourceClient-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/rampart-1.7.1.jar file cannot be found.
at org.apache.axis2.deployment.repository.util.DeploymentFileData.setClassLoader(DeploymentFileData.java:118) [axis2-kernel-1.7.1.jar!/:1.7.1]
at org.apache.axis2.deployment.ModuleDeployer.deploy(ModuleDeployer.java:133) ~[axis2-kernel-1.7.1.jar!/:1.7.1]
at org.apache.axis2.deployment.repository.util.DeploymentFileData.deploy(DeploymentFileData.java:144) [axis2-kernel-1.7.1.jar!/:1.7.1]
at org.apache.axis2.deployment.DeploymentEngine.doDeploy(DeploymentEngine.java:585) [axis2-kernel-1.7.1.jar!/:1.7.1]
at org.apache.axis2.deployment.RepositoryListener.loadClassPathModules(RepositoryListener.java:222) [axis2-kernel-1.7.1.jar!/:1.7.1]
same line when I use "mvn spring-boot:run" is
2017-11-17 16:13:14.270 WARN 7823 --- [nio-8080-exec-9] o.a.axis2.deployment.AxisConfigBuilder : Unable to instantiate deployer org.apache.axis2.deployment.ServiceDeployer; see debug logs for more details
2017-11-17 16:13:14.286 INFO 7823 --- [nio-8080-exec-9] o.a.axis2.deployment.DeploymentEngine : No services directory was found under /home/mehdi/Workspace/EclipseWS/src/main/resources/axis.
2017-11-17 16:13:14.301 INFO 7823 --- [nio-8080-exec-9] o.a.axis2.deployment.ModuleDeployer : Deploying module: rampart-1.7.1 - file:/home/mehdi/Workspace/EclipseWS/src/main/resources/axis/modules/rampart-1.7.1.mar
2017-11-17 16:13:14.304 INFO 7823 --- [nio-8080-exec-9] o.a.axis2.deployment.ModuleDeployer : Deploying module: rampart-1.7.1 - file:/home/mehdi/.m2/repository/org/apache/rampart/rampart/1.7.1/rampart-1.7.1.jar
Please notice that it fails for:
...The rampart-1.7.1.jar module, which is not valid,...
I don't know why with maven launch it works but with java -jar throws exception.
According to Spring Boot documentation (Further Config section) in here
I needed to add the rampart library to unpacked list in spring-boot-maven-plugin as follows:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<requiresUnpack>
<requiresUnpack>
<groupId>org.apache.rampart</groupId>
<artifactId>rampart</artifactId>
</requiresUnpack>
</requiresUnpack>
</configuration>
</plugin>

Spring Cloud Config Client - could not resolve placeholder

I am getting the below error
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'rate' in string value "${rate}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-4.3.5.RELEASE.jar:4.3.5.RELEASE]
The spring boot version used is
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
The yml file of server is
server:
port: 9000
spring:
cloud:
config:
server:
git:
uri: https://github.com/kswat/microservices
search-paths:
- 'station*'
The server starts fine and at port 9000.
Client project:
Using same version of spring boot.
spring:
application:
name: s1rates
profiles:
active: default
cloud:
config:
uri: http://localhost:9000
enabled: true
Controller code:
#RestController
public class RateController {
#Value("${rate}")
String rate;
#RequestMapping("/rate")
public String getRate(){
return rate;
}
}
Is there limitation on port 8888?
why my client starts with looking for 8888
:: Spring Boot :: (v1.4.3.RELEASE)
2017-03-24 13:04:51.348 INFO 1048 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:8888
2017-03-24 13:04:52.479 WARN 1048 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/s1rates/default": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
2017-03-24 13:04:52.483 INFO 1048 --- [ main] c.b.samples.M2ConfigclientApplication : The following profiles are active: default
2017-03-24 13:04:52.518 INFO 1048 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#e84a8e1: startup date [Fri Mar 24 13:04:52 GMT 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#70325e14
2017-03-24 13:04:53.492 WARN 1048 --- [ main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance #Configuration bean definition 'refreshScope' since its singleton instance has been created too early. The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2017-03-24 13:04:53.657 INFO 1048 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=d17fb23f-878c-3e56-87f0-af48d4c36965
2017-03-24 13:04:53.743 INFO 1048 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$4e824d73] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-03-24 13:04:54.178 INFO 1048 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-03-24 13:04:54.194 INFO 1048 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
If I use 8888 in config server, then client works cleanly, without exception.
What is 8888 magic and why I have to stick to it? Is this boot version issue or my mistake?
Resolved -
Changed cloud client project application.yml filename to bootstrap.yml
port 9000 of server works
bootstrap.yml gets loaded before application.yml
Very important, the client application name needs to be the same as the properties name in the repository.For example,your config client application name is config-client,then your properties file in your repository should be config-client-dev.properties.Or you will get the Could not resolve placeholder ${xxx} error.
Add the below dependency in your pom.xml file
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
The client application name needs to be the same as the properties name in the repository. For example, your config client application name is config-client, then your properties file in your repository should be config-client-dev.properties. Or you will get the "Could not resolve placeholder ${xxx}" error.
Spring cloud server that uses git as a property source works with the repository in git style, so it can use different branches, and what`s important regarding the question - the changes must be committed for being visible.

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