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

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.

Related

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>

Slow startup on spring integration test. Cause? Can't disable RabbitMQ

I'm struggling in a performance problem on startup with my integration tests.
I'm trying to mock the messaging of the system. To do that, I basically use #MockBean on my gateway and use #EnableAutoConfiguration(exclude = {RabbitAutoConfiguration.class}). Example:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MyApplication.class)
#WebAppConfiguration
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
#ActiveProfiles("test")
#EnableAutoConfiguration(exclude = {RabbitAutoConfiguration.class})
public class MyTestIT {
These two configuration did the job very well, my tests run without problem and without any dependency with some external RabbitMQ.
But the startup time of the spring boot is very, very slow. It's about two minutes only in this part configuring SimpleMessageListenerContainer, AmqpInboundChannelAdapter, EventDrivenConsumer, RabbitExchangeQueueProvisioner, etc.
The log has some tips about what is the problem (I cut a lot of the messages, this is a sample):
2018-02-09 14:26:37.784 INFO [ms-project-name-service,,,] 13804 --- [ main] o.s.integration.channel.DirectChannel : Channel 'ms-project-name-service:test:-1.channel2-output' has 1 subscriber(s).
2018-02-09 14:26:54.110 INFO [ms-project-name-service,,,] 13804 --- [ main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: channel1-input.anonymous.417FtxKTTce7-_IR0tGuNA, bound to: channel1-input
2018-02-09 14:27:00.147 INFO [ms-project-name-service,,,] 13804 --- [ main] o.s.c.stream.binder.BinderErrorChannel : Channel 'ms-project-name-service:test:-1.channel1-input.anonymous.417FtxKTTce7-_IR0tGuNA.errors' has 2 subscriber(s).
2018-02-09 14:27:09.186 INFO [ms-project-name-service,,,] 13804 --- [ce7-_IR0tGuNA-1] o.s.a.r.l.SimpleMessageListenerContainer : Restarting Consumer#4f0ea6f8: tags=[{}], channel=null, acknowledgeMode=AUTO local queue size=0
The most strange is this one:
2018-02-09 14:58:42.783 WARN [ms-project-name-service,,,] 208 --- [geGeQP_9Li3Jg-1] o.s.a.r.l.SimpleMessageListenerContainer : Consumer raised exception, processing can restart if the connection factory supports it. Exception summary: org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
This last one seems that he is still trying to connect on a local RabbitMQ.
There are a lot of these messages on the log. I can't understand why this is still happening even with RabbitMQAutoConfiguration disabled. It's a mystery too how the spring is subscribing in a channel if there is no RabbitMQ to connect.
We had similar problem here and it was solved by changing the runner:
#RunWith(SpringRunner.class)
to
#RunWith(SpringJUnit4ClassRunner.class)
They seems like the same on the documentation, but really kickoff our test performance.
Let me know if it work, I'm still looking into the documentation for more details.
After #Marco response, the problem was back after I removed the follow dependency of my pom.xml (for instance, it is my first dependency on <dependencies/>:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-test-support</artifactId>
<scope>test</scope>
</dependency>
After return the dependency, the problem was soved. I changed to SpringRunner.class and the tests continued to be fast. I removed the dependency and the tests turned slow again...
I think it's a bug related with the Spring looking for the classpath to do the auto configuration.
By the way, some of the messages on log continues to happen, but they not take so long.
Other thing that help is use this configuration for your tests:
#Configuration
public class RabbitMqConfiguration {
#Bean
ConnectionFactory connectionFactory() {
return new CachingConnectionFactory();
}
}

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

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.

Spring Cloud Config + Spring Cloud Bus + RabbitMQ - Not auto refreshing clients with local Git repository

I have some applications getting its configuration from a Spring Cloud Config Server (Brixton.RELEASE) and would like to enable the auto refresh of its properties. I have followed Spring Cloud Config documentation to configure both the server and client apps but, when making changes on the local git files nothing happens.
the default configuration also detects filesystem changes in local git
repositories (the webhook is not used in that case but as soon as you
edit a config file a refresh will be broadcast).
Can anybody point out what could be wrong or where to debug in Spring Cloud's code to check it?
Spring cloud Server Config:
server:
port: 8888
info:
description: Spring Cloud Config Server
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: file:///C:/Users/myuser/git/config-dev/
Spring Cloud Server pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-monitor</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
Spring Cloud Config Startup logs:
o.s.i.monitor.IntegrationMBeanExporter : Registering MessageChannel springCloudBusInput
o.s.i.monitor.IntegrationMBeanExporter : Located managed bean 'org.springframework.integration:type=MessageChannel,name=springCloudBusInput': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=springCloudBusInput]
o.s.i.monitor.IntegrationMBeanExporter : Registering MessageChannel springCloudBusOutput
o.s.i.monitor.IntegrationMBeanExporter : Located managed bean 'org.springframework.integration:type=MessageChannel,name=springCloudBusOutput': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=springCloudBusOutput]
o.s.i.monitor.IntegrationMBeanExporter : Registering MessageChannel errorChannel
o.s.i.monitor.IntegrationMBeanExporter : Located managed bean 'org.springframework.integration:type=MessageChannel,name=errorChannel': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=errorChannel]
o.s.i.monitor.IntegrationMBeanExporter : Registering MessageChannel nullChannel
o.s.i.monitor.IntegrationMBeanExporter : Located managed bean 'org.springframework.integration:type=MessageChannel,name=nullChannel': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=nullChannel]
o.s.i.monitor.IntegrationMBeanExporter : Located managed bean 'org.springframework.integration:type=MessageHandler,name=errorLogger,bean=internal': registering with JMX server as MBean [org.springframework.integration:type=MessageHandler,name=errorLogger,bean=internal]
o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -2147482648
o.s.c.s.binding.BindableProxyFactory : Binding outputs for :interface org.springframework.cloud.bus.SpringCloudBusClient
o.s.c.s.binding.BindableProxyFactory : Binding :interface org.springframework.cloud.bus.SpringCloudBusClient:springCloudBusOutput
s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#707ca986: startup date [Fri May 13 10:03:10 CEST 2016]; root of context hierarchy
trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$73faa1d3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
o.s.cloud.commons.util.InetUtils : Cannot determine local hostname
e.m.a.config.ConfigServerApplication : No active profile set, falling back to default profiles: default
s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#1ca610a0: startup date [Fri May 13 10:03:11 CEST 2016]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#294a6b8e
o.s.c.support.GenericApplicationContext : Refreshing org.springframework.context.support.GenericApplicationContext#6048e26a: startup date [Fri May 13 10:03:11 CEST 2016]; root of context hierarchy
e.m.a.config.ConfigServerApplication : Started ConfigServerApplication in 2.907 seconds (JVM running for 12.366)
o.s.a.r.c.CachingConnectionFactory : Created new connection: SimpleConnection#7bbcf6f0 [delegate=amqp://guest#127.0.0.1:5672/]
o.s.i.endpoint.EventDrivenConsumer : Adding {message-handler:outbound.springCloudBus} as a subscriber to the 'springCloudBusOutput' channel
o.s.integration.channel.DirectChannel : Channel 'config-server:8888.springCloudBusOutput' has 1 subscriber(s).
o.s.i.endpoint.EventDrivenConsumer : started outbound.springCloudBus
o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -2147482648
o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
o.s.i.channel.PublishSubscribeChannel : Channel 'config-server:8888.errorChannel' has 1 subscriber(s).
o.s.i.endpoint.EventDrivenConsumer : started _org.springframework.integration.errorLogger
o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147482647
o.s.c.s.binding.BindableProxyFactory : Binding inputs for :interface org.springframework.cloud.bus.SpringCloudBusClient
o.s.c.s.binding.BindableProxyFactory : Binding :interface org.springframework.cloud.bus.SpringCloudBusClient:springCloudBusInput
o.s.c.s.b.r.RabbitMessageChannelBinder : declaring queue for inbound: springCloudBus.anonymous.t4cuHSE6RfKRYvPvrgfbUg, bound to: springCloudBus
o.s.integration.channel.DirectChannel : Channel 'springCloudBus.anonymous.t4cuHSE6RfKRYvPvrgfbUg.bridge' has 1 subscriber(s).
o.s.i.a.i.AmqpInboundChannelAdapter : started inbound.springCloudBus.anonymous.t4cuHSE6RfKRYvPvrgfbUg
Client App pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
Client App config:
spring:
application:
name: app
cloud:
config:
uri: http://localhost:8888
Client App Startup log:
o.s.b.a.e.m.EndpointHandlerMapping INFO - Mapped "{[/bus/refresh],methods=[POST]}" onto public void org.springframework.cloud.bus.endpoint.RefreshBusEndpoint.refresh(java.lang.String)
...
o.s.i.m.IntegrationMBeanExporter INFO - Registering beans for JMX exposure on startup
o.s.i.m.IntegrationMBeanExporter INFO - Registering MessageChannel springCloudBusInput
o.s.i.m.IntegrationMBeanExporter INFO - Located managed bean 'org.springframework.integration:type=MessageChannel,name=springCloudBusInput': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=springCloudBusInput]
o.s.i.m.IntegrationMBeanExporter INFO - Registering MessageChannel springCloudBusOutput
o.s.i.m.IntegrationMBeanExporter INFO - Located managed bean 'org.springframework.integration:type=MessageChannel,name=springCloudBusOutput': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=springCloudBusOutput]
o.s.i.m.IntegrationMBeanExporter INFO - Registering MessageChannel nullChannel
o.s.i.m.IntegrationMBeanExporter INFO - Located managed bean 'org.springframework.integration:type=MessageChannel,name=nullChannel': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=nullChannel]
o.s.i.m.IntegrationMBeanExporter INFO - Registering MessageChannel errorChannel
o.s.i.m.IntegrationMBeanExporter INFO - Located managed bean 'org.springframework.integration:type=MessageChannel,name=errorChannel': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=errorChannel]
o.s.i.m.IntegrationMBeanExporter INFO - Located managed bean 'org.springframework.integration:type=MessageHandler,name=org.springframework.cloud.bus.BusAutoConfiguration.acceptRemote.serviceActivator,bean=endpoint': registering with JMX server as MBean [org.springframework.integration:type=MessageHandler,name=org.springframework.cloud.bus.BusAutoConfiguration.acceptRemote.serviceActivator,bean=endpoint]
o.s.i.m.IntegrationMBeanExporter INFO - Located managed bean 'org.springframework.integration:type=MessageHandler,name=errorLogger,bean=internal': registering with JMX server as MBean [org.springframework.integration:type=MessageHandler,name=errorLogger,bean=internal]
o.s.b.a.e.j.EndpointMBeanExporter INFO - Registering beans for JMX exposure on startup
Try to go through this documentation spring-cloud-config-push-notifications and do not forget to install ngrock. Also if you just need to refresh on git commit then you do not even need cloud-bus project just config should be enough. Hope this helps.
You would need a Config server with Spring Cloud Bus and RabbitMQ (or Kafka or Redis) support.
...
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-monitor</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
...
RabbitMQ with the following exchange:
name: springCloudBus
type: topic
durable: true
autoDelete: false
internal: false
The Config server would send data to the topic once it receives push events from any of Github, Bitbucket or GitLab, via a webhook to http://<config-server>/monitor
And a client application with Config and RabbitMQ libraries:
...
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
...
Subscribed to the previous exchange to receive messages with the properties that need to be refreshed.
More could be found in my blog at: http://tech.asimio.net/2017/02/02/Refreshable-Configuration-using-Spring-Cloud-Config-Server-Spring-Cloud-Bus-RabbitMQ-and-Git.html with a brief explanation of the configuration, logs and full source code for the Config server and client app.
You need have fallowing dependent in the pom.xml
compile('org.springframework.cloud:spring-cloud-stream-binder-rabbit') - Gradle
if you have hosed you rabbitmq in the another system you need to specify the host file in the application.properties
spring.rabbitmq.host: {{hostname}}

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