for the project I'm currently working at there is the requirement to disable the webapp context to be started when spring fails to initialize some beans (that call webservices during initialization and therefore are likely to crash then).
However, when a bean throws any exception during initialization, it looks like this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'latestAdsRepository' defined in file [...]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [...]: Constructor threw exception; nested exception is java.io.IOException: SHUT DOWN NOW!!
...
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [...]: Constructor threw exception; nested exception is java.io.IOException: SHUT DOWN NOW!!
however the context starts and all references to the bean that was not able to start are null. Needless to say, this causes various bad Nullpointer Exceptions all over the place. Especially because this bean is very important for the webapp.
So I need a way to explicitly tell Spring that this webapp has failed to start if a bean could not be initialized. System.exit(1) however is not an option, because there are also other webapps on this Tomcat server.
Any ideas?
As far as I know, by default, the context startup fails when Spring fails to instantiate a bean, if the exception is propagated through the startup listener to the servlet container.
You can use the #Required annotation to mark a certain injection point as mandatory.
How are you loading the Spring context?
Sounds like you might be doing it manually (i.e. you are calling new ApplicationContext() somewhere), instead you should use the ContextLoaderListener so that your context is loaded automatically upon application startup (and shutdown during application shutdown). Exceptions during the Spring context startup will propogate to failing the web application context startup.
Related
I'm using the code from here to restart my Spring Boot application:
Thread restartThread = new Thread(() -> restartEndpoint.restart());
restartThread.setDaemon(false);
restartThread.start();
However, the restarted application fails to create beans, ultimately due to a RejectedExecutionException thrown when trying to schedule #Scheduled-annotated methods:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBean' defined in URL [insert-path-here]: Initializetion of bean failed; nested exception is org.springframework.core.TaskRejectedException: Executor [java.util.concurrent.ScheduledThreadPoolExecutor#284a4a89[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 21508]] did not accept task: my.package.MyBean.scheduledMethod
The logs immediately after the doRestart() invocation indicate that the ExecutorService taskScheduleris being shut down, which would explain why this is happening. What I'm not entirely sure of is why the ExecutorService isn't recreated. Embarrassingly enough, it turns out that taskScheduler was a bean defined by my application and was not annotated #RefreshScope. Now the error I'm getting is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'anotherBean' definen in URL[...]: Unsatisfied dependency expressed through constructor parameter 0 ... nested exception is java.lang.IllegalStateException: org.springframework.boot.servlet.context.AnnotationConfigServletWebServerApplicationContext#2a95076c has been closed already
Scrolling up a bit in the logs reveals that there's an ApplicationContextException thrown with the stacktrace containing doRestart:
org.springframework.ApplicationContextException: Unable to start web server; nested exception is java.lang.IllegalStateException: Filters cannot be added to context [/myapp] as the context has been initialized
at org.springframework.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:157)
...
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.cloud.context.restart.RestartEndpoint(RestartEndpoint.java:160)
at my.package.MyBean.lambda$doThingAndRestart$2 (MyBean.java: 118)
Googling this error seems to result in a single page that isn't relevant, although I do note that this application is running on tomcat as well.
I suspect that this is related to the application creating a wrong sort of application context, which is a AnnotationConfigServletWebServerApplicationContext, which doesn't extend AbstractRefreshableAplicationContext.
What do I need to do to get rid of this error?
Please bear with me when I only copy single lines from the stack trace. I'm on a two-computer set-up, so I can't copy-and paste and am no allowed to otherwise move the logs to a computer connected to the Internet.
It turns out that RestartEndpoint only works with Spring's internal Tomcat, not an external one. So, another solution is required. The ones I discovered are
Using Tomcat's WatchedResource to re-deploy the server when a configuration file is overwritten. This has the downside of needing to maintain the Tomcat configuration when maintaining the doThingAndRestart functionality.
Using Tomcat's Manager App. I noticed that the reload request blocks until the app is done reloading, which overflowed the heap space.
Using Spring's RefreshEndpoint. For whatever reason, this didn't refresh the datasources.
Im fairly new to spring mvc and Im trying to launch a extremely simple project that will just display a greeting on a blank page but for some reason I cannot seem to get it to run on the tomcat server, I have gone over every little piece of code and I do not believe there are any mistakes as well as made sure that the tomcat server is configured correctly, any help anyone can give me would be appreciated (This isn't any kind of assignment for anything , this is purely for me trying to learn Spring MVC and learning the proper configuration, because after researching for hours I cannot find anything wrong with it)
I also did this purely in java, no xml. Did not use any dependency managers either ( No Maven or Gradle ) but I do have all necessary jars
I first start by configuring the dispatcher servlet and pass it the webConfig so that the application context can load beans via component scan, since this is a simple project I have no RootConfig class
In my WebConfig I enable Spring MVC ,I give ComponentScan the base package that will search for all Controller classes to create beans for the application context and I create a simple view resolver that will wrap view names with the specified prefix and suffix
My Controller again is really simple I annotate the class as the default handler for "/" requests and map the sayHello method to handle requests for "/home" where I attach a simple message to the model(map) and return the view name
And finally my view which displays the message, The tags in the header of the jsp I know are useless since I'm not using any tags in the form they are just something left over from a previous attempt
When I run this application on the tomcat server I get the following, Im running Tomcat 7 which does support spring mvc java configuration
The tomcat server is running properly
Project is in the webapps directory of tomcat server
And to the best of my knowledge the server configurations are correct
Console output
- Solution -
As mentioned below in the comments the warning I got was
SpringProjLibs is a user library I created and placed all my spring jars inside
This comment along with some research on this warning led me to realize I had failed to add the library to the deployment assembly like below (the entry highlighted in blue was not there , I added that) after adding the line in blue it solved that problem
IMPORTANT
Im adding a follow up to this post since this still pertains to my original question. After completing the above step it resolved THAT issue but another issue presented itself.
I got the following error and tomcat failed to launch
Jun 18, 2018 5:57:37 PM
org.springframework.web.servlet.DispatcherServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'requestMappingHandlerAdapter' defined in
class
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration:
Instantiation of bean failed; nested exception is
org.springframework.beans.factory.BeanDefinitionStoreException:
Factory method [public
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.requestMappingHandlerAdapter()]
threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'mvcValidator' defined in class
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration:
Invocation of init method failed; nested exception is
java.lang.NoClassDefFoundError: com/fasterxml/classmate/Filter
After doing some research I discovered that contrary to what ive studied and seen in online material the annotations #EnableWebMvc and #ComponentScan together in the WebConfig class were causing this issue. I resolved this issue by moving the #EnableWebMvc annotation to the Initializer class , now my classes look like the following
This resolved all my issues and my project launched successfully
We have an application that creates beans on startup using Spring's AnnotationConfigApplicationContext. What we're trying to do is not have Spring destroy all the beans created and thus cause the app fail on startup if creation of one of the beans fails. Is there any native Spring config or way to accomplish this?
I tried overriding the AnnotationConfigApplicationContext with my own Custom AnnotationConfigApplicationContext and catching exceptions within there. What was happening though is when an exception was thrown, all remaining beans were not created.
We're using Spring 4.3.0.
easy way to deal with this is by lazy initialization of bean using attribute lazy-init="true" in your bean declaration
I'm implementig a page that has a search field and is calling a elasticsearch service using spring.
The connection to the elasticsearch engine was done by using the spring bean provided by spring-elasticsearch (https://github.com/dadoonet/spring-elasticsearch):
<elasticsearch:client id="esClient" esNodes="localhost:9300" />
This worked well but I want to move my engine to a different server, so to development and test I created an app in Openshift with elasticsearch using this https://github.com/caruccio/openshift-elasticsearch and change the transported client esNode link. The problem here is always giving me errors like this one (or similar to this one):
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.projectx.standard.services.common.SearchEngineService com.projectx.standard.app.controler.common.IndexController.searchEngineService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchEngineService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.elasticsearch.client.Client com.projectx.standard.services.common.implementation.ElasticSearchServiceImpl.esClient; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'esClient': Invocation of init method failed; nested exception is java.lang.NumberFormatException: For input string: "//elastic-projectxserver.rhcloud.com/"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
I think the problem is in the link because I'm using the http://... in the esNodes field, but I'm not sure.
Someone know how to put the application to connect to an engine in the openshift?
btw, I found this https://github.com/spring-projects/spring-data-elasticsearch that looks interesting but I don't know if this will help solve my problem or is worth to change!
Thanks in advance
This will not work as the https://github.com/dadoonet/spring-elasticsearch code is expecting the configuration in the form of host:port. Looking at the exception, you are providing as host as http://elastic-projectxserver.rhcloud.com/. The library will split it by : and you will //elastic-projectxserver.rhcloud.com/ as port. This is the reason you are getting NumberFormatException as port should be an int. In your client configuration, try using elastic-projectxserver.rhcloud.com:80.
Also, I would recommend you use https://github.com/spring-projects/spring-data-elasticsearch as that is official Spring ElasticSearch library.
Recently I added JMX support to my Spring web application.
This works fine for beans with #Component, however, for some services there seems to be a problem when adding #ManagedResource
I have a spring service annotated with #Service method.
I'm trying to add JMX to that service using #ManagedResource but it seems like spring is having troubles registering the beans:
org.springframework.beans.factory.BeanCreationException:
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'mbeanExporter': Invocation of init method
failed; nested exception is
org.springframework.jmx.export.UnableToRegisterMBeanException: Unable
to register MBean [...] with key 'appAnalysisServiceImpl'; nested
exception is org.springframework.jmx.export.MBeanExportException:
Could not create ModelMBean for managed resource [
l#6142152] with key 'myservice'; nested exception is java.lang.IllegalArgumentException: MetadataMBeanInfoAssembler does
not support JDK dynamic proxies - export the target beans directly or
use CGLIB proxies instead
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
From the exception message it seems like spring requires a special exporter for this kind of class.
How do i export the bean directly without writing my own exporter ?
If your service uses #Transactional then Spring won't be able to create a ModelBean since the service is proxied.