resteasy ContainerRequestFilter didn't work in springboot - spring-boot

resteasy 3.1.3.Final and springboot 1.5.7
I want do somthing before the request go ino the restful method,but it never worked.
here is the restful method interface.
#Path("/demo")
#Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public interface DemoService {
#POST
#Path("/query")
List<EntityDemoInfo> queryByType(QueryRequest requst);
}
Here is the filter.
#Provider
#PreMatching
public class RequestFilter implements HttpRequestPreprocessor,ContainerRequestFilter{
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
System.out.println("-----------------");
}
#Override
public void preProcess(HttpRequest request) {
System.out.println("================");
}
}
It never go in the filter and print the log,even if i tried the annotations #Provider/#PreMatching/#Configuration in any combination.
Later i think maybe something registry problem,and tried to add #Bean in #SpringBootApplication class.This can print what I register,however when debugging request the registry/factory din't have my RequestFilter, thus it didn't work. What's wrong with it? thanks !
#Bean
public SynchronousDispatcher synchronousDispatcher() {
ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
RequestFilter requestFilter = new RequestFilter();
providerFactory.getContainerRequestFilterRegistry().registerSingleton(requestFilter);
SynchronousDispatcher dispatcher = new SynchronousDispatcher(providerFactory);
dispatcher.addHttpPreprocessor(requestFilter);
System.out.println("*****************");
System.out.println(providerFactory.getContainerRequestFilterRegistry().preMatch());
return dispatcher;
}
As 'paypal' codes do in https://github.com/paypal/resteasy-spring-boot , I added RequestFilter like Hantsy mentioned below, it didn't work!
Here is the log.
14:44:01.537 [main] INFO org.apache.tomcat.util.net.NioSelectorPool Using a shared selector for servlet write/read
14:44:01.548 [main] INFO org.jboss.resteasy.resteasy_jaxrs.i18n RESTEASY002225: Deploying javax.ws.rs.core.Application: class com.sample.app.JaxrsApplication
#################
################# ------This is what I add in JaxrsApplication
14:44:01.548 [main] INFO org.jboss.resteasy.resteasy_jaxrs.i18n RESTEASY002215: Adding singleton provider java.lang.Class from Application class com.sample.app.JaxrsApplication
14:44:01.554 [main] INFO org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer Tomcat started on port(s): 8080 (http)
14:44:01.559 [main] INFO com.sample.app.Application Started Application in 2.478 seconds (JVM running for 2.978)
//There is when i post a request as it say what happened,nothing,but got the response.Thus it didn't work!
14:45:58.657 [RMI TCP Connection(2)-127.0.0.1] INFO org.springframework.boot.admin.SpringApplicationAdminMXBeanRegistrar$SpringApplicationAdmin Application shutdown requested.
14:45:58.657 [RMI TCP Connection(2)-127.0.0.1] INFO org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#34f22f9d: startup date [Fri Oct 20 14:43:59 CST 2017]; root of context hierarchy
14:45:58.659 [RMI TCP Connection(2)-127.0.0.1] INFO org.springframework.context.support.DefaultLifecycleProcessor Stopping beans in phase 0
14:45:58.660 [RMI TCP Connection(2)-127.0.0.1] INFO org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter Unregistering JMX-exposed beans on shutdown
14:45:58.660 [RMI TCP Connection(2)-127.0.0.1] INFO org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter Unregistering JMX-exposed beans
14:45:58.660 [RMI TCP Connection(2)-127.0.0.1] INFO org.springframework.jmx.export.annotation.AnnotationMBeanExporter Unregistering JMX-exposed beans on shutdown

The resteasy documentation provides simple guide for intgrating resteasy with Spring and Spring Boot. Hope these links are helpful.
Resteasy and Spring Integration
Spring Boot starter, described in the 43.4. Spring Boot starter section of the Resteasy doc.
If you are using Spring Boot as described in the doc, just register you custom Filter in your Application class.
#Component
#ApplicationPath("/sample-app/")
public class JaxrsApplication extends Application {
#Override
public Set<Object> getSingletons() {
Set<Object> singletons = new HashSet<>();
singletons.add(yourFilter);
return singletons;
}
}
Updated: I forked the paypal/resteasy-spring-boot, and modified the sample-app, added a EchoFitler for demo purpose.
Check the source codes from my Github account.
Run the sample-app via mvn spring-boot:run.
Use curl to test the apis.
# curl -v -X POST -H "Content-Type:text/plain" -H "Accept:application/json" http://localhost:8080/sample-app/echo -d "test"
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> POST /sample-app/echo HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.56.0
> Content-Type:text/plain
> Accept:application/json
> Content-Length: 4
>
* upload completely sent off: 4 out of 4 bytes
< HTTP/1.1 200
< X-Application-Context: application
< Content-Type: application/json
< Content-Length: 45
< Date: Fri, 20 Oct 2017 07:19:43 GMT
<
{"timestamp":1508483983603,"echoText":"test"}* Connection #0 to host localhost left intact
And you will see the filtering info in the spring-boot console.
filtering request context:org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext#1ca8d1e4
filtering request/response context:org.jboss.resteasy.core.interception.jaxrs.ResponseContainerRequestContext#1787a18c
org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl#4aad828e
Hope this is helpful.

Related

Spring Boot WS-Server - Custom Http Status

I published endpoints using Spring Boot WS-Server
When I use SoapUI I see:
HTTP/1.1 200
Accept: text/xml, text/html, image/gif, image/jpeg, *; q=.2, /; q=.2
SOAPAction: ""
Content-Type: text/xml;charset=utf-8
Content-Length: 828
Date: Thu, 29 Apr 2021 14:04:54 GMT
Keep-Alive: timeout=60
Connection: keep-alive
I would like to set custom HTTP Status in response (I know that it may be against the standard but it is an external requirement). I also read following topic:
Spring WS (DefaultWsdl11Definition) HTTP status code with void
But this solution failed
Spring Boot version: 2.2.7
Problem was solved
As I said I wanted to set custom HTTP status in SOAP response.
I found this post:
Spring WS (DefaultWsdl11Definition) HTTP status code with void
Author used EndpointInterceptor with TransportContext to get HttpServletResponse, then he changed status. The difference between my and his case is the fact, that he returned void from WebService method whereas I wanted to return some response.
In my situation following code in Spring WebServiceMessageReceiverObjectSupport class (method handleConnection) overrode servlet status previously set in interceptor:
if (response instanceof FaultAwareWebServiceMessage && connection instanceof FaultAwareWebServiceConnection) {
FaultAwareWebServiceMessage faultResponse = (FaultAwareWebServiceMessage)response;
FaultAwareWebServiceConnection faultConnection = (FaultAwareWebServiceConnection)connection;
faultConnection.setFaultCode(faultResponse.getFaultCode());
}
In order to bypass this fragment of code I needed to define class with my own implementation of handleConnection method, which extended class WebServiceMessageReceiverHandlerAdapter
In my implementation I excluded change of status. Important thing is to pass WebMessageFactory bean in autowired constructor of this class, otherwise exception is raised during app's startup.
This class has to be marked with Spring stereotype (eg. #Component) and name of this bean has to be configured in Configuration class when configuring ServletRegistrationBean:
#Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext applicationContext){
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
servlet.setMessageFactoryBeanName("webServiceMessageFactory");
servlet.setMessageReceiverHandlerAdapterBeanName("myOwnMessageReceiverHandlerAdapter");
return new ServletRegistrationBean<>(servlet,"/ws/*");
}

HikariCP restart with Spring Cloud Config

I have recently configured my application to use Spring Cloud Config with Github as a configuration repository.
Spring Boot - 2.1.1.RELEASE
Spring Cloud Dependencies - Greenwich.RC2
My application is using pretty much everything out of the box. I have just configured the database in application.yml and I have HikariCP autoconfigurations doing the magic in the background.
I am refreshing my applications using this job that calls refresh() method on the RefreshEndpoint.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.endpoint.RefreshEndpoint;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#EnableScheduling
#Component
public class ConfigRefreshJob {
private static final Logger LOG = LoggerFactory.getLogger(ConfigRefreshJob.class);
private static final int ONE_MINUTE = 60 * 1000;
private final RefreshEndpoint refreshEndpoint;
#Autowired
public ConfigRefreshJob(final RefreshEndpoint refreshEndpoint) {
this.refreshEndpoint = refreshEndpoint;
}
#Scheduled(fixedDelay = ONE_MINUTE)
public void refreshConfigs() {
LOG.info("Refreshing Configurations - {}", refreshEndpoint.refresh());
}
}
Everything seems be working good, but I see following logs every time I refresh the configurations. These logs say HikariCP pool is shutdown and started everytime I refresh.
2019-01-16 18:54:55.817 INFO 14 --- [taskScheduler-9] o.s.b.SpringApplication : Started application in 0.155 seconds (JVM running for 144.646)
2019-01-16 18:54:55.828 INFO 14 --- [taskScheduler-9] c.z.h.HikariDataSource : HikariPool-1555 - Shutdown initiated...
2019-01-16 18:54:55.828 INFO 14 --- [taskScheduler-9] c.z.h.HikariDataSource : HikariPool-1555 - Shutdown completed.
2019-01-16 18:54:55.828 INFO 14 --- [taskScheduler-9] c.d.ConfigRefreshJob : Refreshing Configurations - []
2019-01-16 18:55:03.094 INFO 14 --- [ XNIO-1 task-5] c.z.h.HikariDataSource : HikariPool-1556 - Starting...
2019-01-16 18:55:03.123 INFO 14 --- [ XNIO-1 task-5] c.z.h.HikariDataSource : HikariPool-1556 - Start completed.
If I look at the times of these logs, it takes around 8 seconds for the HikariCP to be configured again.
I haven't found any issues in my application as of now since the load on the application is not that much right now, but here are couple of questions that I have.
Does this restart of HikariCP cause issues with the load to the application is increased?
If the restarting can cause issues, is there a way to not refresh the HikariCP?
HikariCP is made refreshable by default because a change made to it that seals the configuration once the pool is started.
So disable this, set spring.cloud.refresh.refreshable to an empty set.
Here is the example to configure in yaml
spring:
cloud:
refresh:
refreshable:
- com.example.app.config.ConfigProperties
where ConfigProperties is the class annotated with #RefreshScope.
this worked for me (spring-boot-2.2.7.RELEASE, spring-cloud-Hoxton.SR4)
spring.cloud.refresh.extra-refreshable=com.zaxxer.hikari.HikariDataSource

AWS Lambda - Spring boot is not handling the request

I am trying to run spring boot application as serverless in AWS lambda and I am getting below exception while calling lambda function. Spring boot application successfully ran but it seems that it is going to fail to map the request
2018-09-25 06:11:50.717 INFO 1 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-09-25 06:11:50.823 INFO 1 --- [ main] **my.service.Application : Started Application in 7.405 seconds (JVM running for 8.939)**
START RequestId: decfc13c-c089-11e8-bacd-a37f1ba65629 Version: $LATEST
2018-09-25 06:11:50.994 ERROR 1 --- [ main] **c.a.s.p.i.s.AwsProxyHttpServletRequest : Called set character encoding to UTF-8 on a request without a content type. Character encoding will not be set
2018-09-25 06:11:51.175 ERROR 1 --- [ main] o.s.boot.web.support.ErrorPageFilter : Forwarding to error page from request [/] due to exception [null]**
java.lang.NullPointerException: null
at com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest.getRemoteAddr(AwsProxyHttpServletRequest.java:575) ~[task/:na]
at org.springframework.web.servlet.FrameworkServlet.publishRequestHandledEvent(FrameworkServlet.java:1075) ~[task/:na]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[task/:na]
.........
2018-09-25 06:11:51.535 ERROR 1 --- [ main] s.p.i.s.AwsLambdaServletContainerHandler : Could not forward request
This is my StreamLambdaHandler java file.
public class StreamLambdaHandler implements RequestStreamHandler {
private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
static {
try {
handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);
} catch (ContainerInitializationException e) {
throw new RuntimeException("Could not initialize Spring Boot application", e);
}
}
#Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
handler.proxyStream(inputStream, outputStream, context);
outputStream.close();
}
}
Looks like you might be hitting https://github.com/awslabs/aws-serverless-java-container/issues/172. According to the ticket, the fix will be available as part of the upcoming 1.2 release.

Spring Integration - MQTT subscription issue

I am trying to implement Spring integration with MQTT. I am using Mosquitto as MQTT broker. with the reference to docs provided in the following link. I have created a project and added all the required jar files. when i execute MQTTJavaApplication.
public class MqttJavaApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(MqttJavaApplication.class)
.web(false)
.run(args);
}
#Bean
public MessageChannel mqttInputChannel() {
return new DirectChannel();
}
#Bean
public MqttPahoMessageDrivenChannelAdapter inbound() {
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter("tcp://localhost:1883", "test",
"sample");
adapter.setCompletionTimeout(5000);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
adapter.setOutputChannel(mqttInputChannel());
return adapter;
}
#Bean
#ServiceActivator(inputChannel = "mqttInputChannel")
public MessageHandler handler() {
return new MessageHandler() {
#Override
public void handleMessage(Message<?> message) {
System.out.println("Test##########"+message.getPayload());
}
};
}
}
I am getting following error when i publish a message via MQTT broker.
[2015-11-23 10:08:19.545] boot - 8100 INFO [main] --- AnnotationConfigApplicationContext: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#2d0e1c: startup date [Mon Nov 23 10:08:19 IST 2015]; root of context hierarchy
[2015-11-23 10:08:19.831] boot - 8100 INFO [main] --- PropertiesFactoryBean: Loading properties file from URL [jar:file:/D:/IoTWorkspace/MQTTTest/WebContent/WEB-INF/lib/spring-integration-core-4.2.1.RELEASE.jar!/META-INF/spring.integration.default.properties]
[2015-11-23 10:08:20.001] boot - 8100 INFO [main] --- DefaultLifecycleProcessor: Starting beans in phase 1073741823
[2015-11-23 10:08:20.104] boot - 8100 INFO [main] --- MqttPahoMessageDrivenChannelAdapter: started inbound
[2015-11-23 10:08:20.112] boot - 8100 INFO [main] --- MqttJavaApplication: Started MqttJavaApplication in 1.602 seconds (JVM running for 2.155)
[2015-11-23 10:13:04.564] boot - 8100 ERROR [MQTT Call: test] --- MqttPahoMessageDrivenChannelAdapter: Unhandled exception for GenericMessage [payload=Testing Subscription, headers={timestamp=1448253784563, id=cd5be974-3b19-8317-47eb-1c139725be24, mqtt_qos=0, mqtt_topic=sample, mqtt_retained=false, mqtt_duplicate=false}]
org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'unknown.channel.name'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:81)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:442)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:392)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:105)
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.messageArrived(MqttPahoMessageDrivenChannelAdapter.java:262)
at org.eclipse.paho.client.mqttv3.internal.CommsCallback.handleMessage(CommsCallback.java:336)
at org.eclipse.paho.client.mqttv3.internal.CommsCallback.run(CommsCallback.java:148)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:153)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:120)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
... 10 more
[2015-11-23 10:13:04.613] boot - 8100 ERROR [MQTT Call: test] --- MqttPahoMessageDrivenChannelAdapter: Lost connection:MqttException; retrying...
[2015-11-23 10:13:04.614] boot - 8100 ERROR [MQTT Call: test] --- MqttPahoMessageDrivenChannelAdapter: Failed to schedule reconnect
java.lang.NullPointerException
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.scheduleReconnect(MqttPahoMessageDrivenChannelAdapter.java:228)
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.connectionLost(MqttPahoMessageDrivenChannelAdapter.java:255)
at org.eclipse.paho.client.mqttv3.internal.CommsCallback.connectionLost(CommsCallback.java:229)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.shutdownConnection(ClientComms.java:339)
at org.eclipse.paho.client.mqttv3.internal.CommsCallback.run(CommsCallback.java:171)
at java.lang.Thread.run(Thread.java:722)
[2015-11-23 10:13:04.617] boot - 8100 INFO [Thread-0] --- AnnotationConfigApplicationContext: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#2d0e1c: startup date [Mon Nov 23 10:08:19 IST 2015]; root of context hierarchy
[2015-11-23 10:13:04.619] boot - 8100 INFO [Thread-0] --- DefaultLifecycleProcessor: Stopping beans in phase 1073741823
[2015-11-23 10:13:04.622] boot - 8100 ERROR [Thread-0] --- MqttPahoMessageDrivenChannelAdapter: Exception while unsubscribing
Client is not connected (32104)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:27)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.sendNoWait(ClientComms.java:132)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.unsubscribe(MqttAsyncClient.java:707)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.unsubscribe(MqttAsyncClient.java:682)
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.doStop(MqttPahoMessageDrivenChannelAdapter.java:124)
at org.springframework.integration.endpoint.AbstractEndpoint.doStop(AbstractEndpoint.java:145)
at org.springframework.integration.endpoint.AbstractEndpoint.stop(AbstractEndpoint.java:128)
at org.springframework.context.support.DefaultLifecycleProcessor.doStop(DefaultLifecycleProcessor.java:229)
at org.springframework.context.support.DefaultLifecycleProcessor.access$300(DefaultLifecycleProcessor.java:51)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.stop(DefaultLifecycleProcessor.java:363)
at org.springframework.context.support.DefaultLifecycleProcessor.stopBeans(DefaultLifecycleProcessor.java:202)
at org.springframework.context.support.DefaultLifecycleProcessor.onClose(DefaultLifecycleProcessor.java:118)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:966)
at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:893)
[2015-11-23 10:13:04.623] boot - 8100 ERROR [Thread-0] --- MqttPahoMessageDrivenChannelAdapter: Exception while disconnecting
Client is disconnected (32101)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:27)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.disconnect(ClientComms.java:405)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.disconnect(MqttAsyncClient.java:524)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.disconnect(MqttAsyncClient.java:493)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.disconnect(MqttAsyncClient.java:500)
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.doStop(MqttPahoMessageDrivenChannelAdapter.java:131)
at org.springframework.integration.endpoint.AbstractEndpoint.doStop(AbstractEndpoint.java:145)
at org.springframework.integration.endpoint.AbstractEndpoint.stop(AbstractEndpoint.java:128)
at org.springframework.context.support.DefaultLifecycleProcessor.doStop(DefaultLifecycleProcessor.java:229)
at org.springframework.context.support.DefaultLifecycleProcessor.access$300(DefaultLifecycleProcessor.java:51)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.stop(DefaultLifecycleProcessor.java:363)
at org.springframework.context.support.DefaultLifecycleProcessor.stopBeans(DefaultLifecycleProcessor.java:202)
at org.springframework.context.support.DefaultLifecycleProcessor.onClose(DefaultLifecycleProcessor.java:118)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:966)
at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:893)
[2015-11-23 10:13:04.624] boot - 8100 INFO [Thread-0] --- MqttPahoMessageDrivenChannelAdapter: stopped inbound
Please find below stack trace after adding #SpringBootApplication Annotation
[2015-11-26 10:55:46.571] boot - 5524 INFO [main] --- AnnotationConfigApplicationContext: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#562d4b: startup date [Thu Nov 26 10:55:46 IST 2015]; root of context hierarchy
[2015-11-26 10:55:46.572] boot - 5524 WARN [main] --- AnnotationConfigApplicationContext: Exception thrown from ApplicationListener handling ContextClosedEvent
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.context.annotation.AnnotationConfigApplicationContext#562d4b: startup date [Thu Nov 26 10:55:46 IST 2015]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:337)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:324)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1025)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:988)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:329)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130)
at com.igate.MqttJavaApplication.main(MqttJavaApplication.java:32)
[2015-11-26 10:55:46.594] boot - 5524 WARN [main] --- AnnotationConfigApplicationContext: Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.context.annotation.AnnotationConfigApplicationContext#562d4b: startup date [Thu Nov 26 10:55:46 IST 2015]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:350)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1033)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:988)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:329)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130)
at com.igate.MqttJavaApplication.main(MqttJavaApplication.java:32)
Exception in thread "main" java.lang.IllegalStateException: At least one base package must be specified
at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:121)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:214)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:149)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:135)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:260)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:203)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:617)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:648)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130)
at com.igate.MqttJavaApplication.main(MqttJavaApplication.java:32)
Yep! That's true. Without #SpringBootApplication I have the same StackTrace.
The Spring Boot stuff includes IntegrationAutoConfiguration who is responsible for subscribers and TaskScheduler bean population.
Probably too late to answer but hope it might help some beginner.
Few Things:-
Declare #SpringBootApplication in your main class to let the project know its a spring boot application
For the 2nd Error, Define base package of the project where spring boot will refer for configuration files etc. To do so, add #ComponentScan({"package-name"}) at class level.
Sample Example:-
#SpringBootApplication
#ComponentScan({"package-name"})
public class Main {
...
}

Spring Web Application: Post-DispatcherServlet initialization

I am using Spring 3.2 DispatcherServlet. I am looking for an initialization hook that takes place after the DispatcherServlet initialization completes; either a standard Spring solution or servlet solution. Any suggestions?
As a point of reference, the final logging statements after servlet startup follow. I want my initialization method to execute right after the configured successfully log statement.
DEBUG o.s.w.s.DispatcherServlet - Published WebApplicationContext of servlet 'mySpringDispatcherServlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.mySpringDispatcherServlet]
INFO o.s.w.s.DispatcherServlet - FrameworkServlet 'mySpringDispatcherServlet': initialization completed in 5000 ms
DEBUG o.s.w.s.DispatcherServlet - Servlet 'mySpringDispatcherServlet' configured successfully
From my research, so far the following have not had the desired effect:
Extending ContextLoaderListener/implementing ServletContextListener per this answer.
Implementing WebApplicationInitializer per the javaoc.
My beans use #PostConstruct successfully; I'm looking for a Servlet or container level hook that will be executed essentially after the container initializes and post-processes the beans.
The root issue was that I couldn't override the final method HttpsServlet.init(). I found a nearby #Override-able method in DispatcherServlet.initWebApplicationContext that ensured my beans and context were fully initialized:
#Override
protected WebApplicationContext initWebApplicationContext()
{
WebApplicationContext wac = super.initWebApplicationContext();
// do stuff with initialized Foo beans via:
// wac.getBean(Foo.class);
return result;
}
From Spring's Standard and Custom Events.
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
#Component
public class ApplicationContextListener implements
ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("ApplicationContext was initialized or refreshed: "
+ event.getApplicationContext().getDisplayName());
}
}
The event above will be fired when the DispatcherServlet is initialized, such as when it prints:
INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'ServletName': initialization completed in 1234 ms
You can implement ApplicationListener<ContextStartedEvent> within your application context. This event listener will then be called once for your root context and once for each servlet context.
public class StartupListener implements ApplicationListener<ContextStartedEvent> {
public void onApplicationEvent(ContextStartedEvent event) {
ApplicationContext context = (ApplicationContext) event.getSource();
System.out.println("Context '" + context.getDisplayName() + "' started.");
}
}
If you define this listener within your servlet context, it should be called just once for the servlet context intself.
try this, change your port number.
In my case i changed from server.port=8001 to server.port=8002

Resources