rabbitConnectionFactory autodetected for JMX exposure - spring-boot

I have a Spring Boot application that supports Kafka. Recently I am trying to make it also support RabbitMQ. I set up the code using the #Profile annotation so that all the new code for RabbitMQ should be active only if I select spring.profiles.active to be rabbit-mq. Likewise, the Kafka-specific code are marked out by profile value of kafka
I was surprise to see that even with the above setup, when I set the profile to be kafka, some RabbitMQ is still included and activated, through a mechanism JMX exposure. Specifically, a rabbitConnectionFactory bean was constructed, and then it tried to do health check with a RabbitMQ broker at localhost:5672, and failed.
In the log file, I saw these messages:
... o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
... o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'rabbitConnectionFactory' has been autodetected for JMX exposure
... o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'rabbitConnectionFactory': registering with JMX server as MBean [org.springframework.amqp.rabbit.connection:name=rabbitConnectionFactory,type=CachingConnectionFactory]
... o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483547
... o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
... o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
... c.s.datacomparatorproducer.Application : Started Application in 5.175 seconds (JVM running for 5.663)
... o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
... o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
... o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 15 ms
... o.s.a.r.c.CachingConnectionFactory : Attempting to connect to: [localhost:5672]
... o.s.b.a.amqp.RabbitHealthIndicator : Rabbit health check failed
org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused (Connection refused)
at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:62) ~[spring-rabbit-2.0.3.RELEASE.jar!/:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:476) ~[spring-rabbit-2.0.3.RELEASE.jar!/:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:614) ~[spring-rabbit-2.0.3.RELEASE.jar!/:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.createConnection(ConnectionFactoryUtils.java:240) ~[spring-rabbit-2.0.3.RELEASE.jar!/:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1797) ~[spring-rabbit-2.0.3.RELEASE.jar!/:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1771) ~[spring-rabbit-2.0.3.RELEASE.jar!/:2.0.3.RELEASE]
I have two questions:
How can I avoid RabbitMQ code from being included? Why my set up using #Profile did not work as expected?
How do I configure the rabbitConnectionFactory? Currently it is trying to talk to localhost:5672. I know how to, in general, set up Spring template to use application-xxx.properties for spring.rabbitmq.{host,port}, but in this case, since the code is auto-included, I don't know how to configure rabbitConnectionFactory
Usual configuration
spring.rabbitmq.host=someRabbitBroker
spring.rabbitmq.port=5672
Update
Attempt 1: Excluding RabbitAutoConfiguration
Thank you Gary Russell for the suggestion. I tried his method and changed my #SpringBootApplication as follows. The idea here is to exclude RabbitAutoConfiguration when spring.rabbitmq.host is NOT defined (when the profile of rabbit-mq is not active):
#SpringBootApplication
public class Application {
#ConditionalOnProperty(value="spring.rabbitmq.host")
#Bean
RabbitAutoConfiguration rabbitAutoConfiguration(){
return new RabbitAutoConfiguration();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I am not sure if this code is the correct way to do it, but it did not work. When my app started, I still saw these in the message:
... o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
... o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'rabbitConnectionFactory' has been autodetected for JMX exposure
... o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'rabbitConnectionFactory': registering with JMX server as MBean [org.springframework.amqp.rabbit.connection:name=rabbitConnectionFactory,type=CachingConnectionFactory]
... o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483547
I am okay with having the bean constructed, as long as I can stop it from doing health check (or at least configure it to use my designated host and port). Is there a way to do this?

You either need to exclude the spring-rabbit jar from the classpath or disable rabbitmq auto-configuration by excluding RabbitAutoConfiguration from the #SpringBootApplication.
Update: disabling health check
See the boot properties documentation. Specifically set management.health.rabbit.enabled to false

Related

Clone of start.spring.io

I'm trying to build an instance of start.spring.io to use it in an air-gaped network. I have been working on it for three weeks and still I don't understand well what to do.
I have cloned start.spring.io from GitHub in a host connected to Internet.
There I can build the application without errors:
./mvnw clean install -DskipTests=true
Then if I true to run the application (../mwnw spring-boot:run from the start-site directory), I get the following error when the application starts, I mean is not an error trying to generate a project, and the application dies:
2022-12-19 17:53:21.170 INFO 2701 --- [ restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
2022-12-19 17:53:21.264 WARN 2701 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [io.spring.initializr.web.controller.ProjectGenerationController] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader#5cb0d902]
2022-12-19 17:53:21.272 INFO 2701 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-12-19 17:53:21.311 INFO 2701 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-12-19 17:53:21.411 ERROR 2701 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [io.spring.initializr.web.controller.ProjectGenerationController] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader#5cb0d902]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$
...
So, I am not adding any special dependencies or initilializr dependencies other than those already included in the project. I use Java 17 from Bell Soft.
I am not about the Spring Boot version but I haven't modified anything in the project. The pom file in the top directory includes:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
</parent>
About my dependencies I am using the initializer-bom:0.20.0-SNAPSHOT. I have also tried with other versions like 0.13.0 and 0.12.0 but the build fails in both cases for the start-site:
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /workspaces/start.spring.io.ori/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudContractKotlinDslGradleBuildCustomizer.java:[44,22] cannot find symbol
symbol: method snippets()
location: variable build of type io.spring.initializr.generator.buildsystem.gradle.GradleBuild
[ERROR] /workspaces/start.spring.io.ori/start-site/src/main/java/io/spring/start/site/extension/dependency/graalvm/HibernatePluginGroovyDslGradleBuildCustomizer.java:[39,22] cannot find symbol
symbol: method snippets()
location: variable build of type io.spring.initializr.generator.buildsystem.gradle.GradleBuild
[ERROR] /workspaces/start.spring.io.ori/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudContractGroovyDslGradleBuildCustomizer.java:[36,22] cannot find symbol
symbol: method snippets()
location: variable build of type io.spring.initializr.generator.buildsystem.gradle.GradleBuild
[INFO] 3 errors
I wonder if this effort makes sense. If I manage to build the application, will I be able of generating code or does the application connect to somewhere else to retrieve the data required to generate the code?
I would appreciate any hints. Thanks
I will write my (potential) answer here, even though I don't really think that is a real answer but too big to make it as a comment.
My setup:
Amazon Coretto JDK 17 https://docs.aws.amazon.com/corretto/latest/corretto-17-ug/downloads-list.html (it is not JDK 17 from Bell Soft)
Windows 11 Home
So I went to https://github.com/spring-io/start.spring.io and cloned it.
git clone https://github.com/spring-io/start.spring.io.git
Then I went in the root directoy of the cloned project and ran following command:
./mvnw clean install
Here I got some errors while running the tests, but this shouldn't be way too tragic - I think they failed for me, because it tries to run some gradlew commands but they do fail, because I don't have Gradle installed on my PC, as I am always using the Gradle Wrapper.
Then I started the Spring Boot Application.
cd start-site
../mvnw spring-boot:run
The Spring Boot Application started:
022-12-20T15:01:03.510+01:00 INFO 16592 --- [ restartedMain] io.spring.start.site.StartApplication : No active profile set, falling back to 1 default profile: "default"
2022-12-20T15:01:03.573+01:00 INFO 16592 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-12-20T15:01:03.573+01:00 INFO 16592 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-12-20T15:01:04.800+01:00 INFO 16592 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-12-20T15:01:04.809+01:00 INFO 16592 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-12-20T15:01:04.810+01:00 INFO 16592 --- [ restartedMain] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.1]
2022-12-20T15:01:04.872+01:00 INFO 16592 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-12-20T15:01:04.873+01:00 INFO 16592 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1298 ms
2022-12-20T15:01:05.371+01:00 INFO 16592 --- [ restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
2022-12-20T15:01:05.823+01:00 INFO 16592 --- [ restartedMain] org.ehcache.core.EhcacheManager : Cache 'initializr.metadata' created in EhcacheManager.
2022-12-20T15:01:05.832+01:00 INFO 16592 --- [ restartedMain] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheConfiguration,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=initializr.metadata
2022-12-20T15:01:05.832+01:00 INFO 16592 --- [ restartedMain] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheStatistics,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=initializr.metadata
2022-12-20T15:01:05.835+01:00 INFO 16592 --- [ restartedMain] org.ehcache.core.EhcacheManager : Cache 'initializr.dependency-metadata' created in EhcacheManager.
2022-12-20T15:01:05.836+01:00 INFO 16592 --- [ restartedMain] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheConfiguration,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=initializr.dependency-metadata
2022-12-20T15:01:05.836+01:00 INFO 16592 --- [ restartedMain] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheStatistics,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=initializr.dependency-metadata
2022-12-20T15:01:05.839+01:00 INFO 16592 --- [ restartedMain] org.ehcache.core.EhcacheManager : Cache 'initializr.project-resources' created in EhcacheManager.
2022-12-20T15:01:05.841+01:00 INFO 16592 --- [ restartedMain] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheConfiguration,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=initializr.project-resources
2022-12-20T15:01:05.841+01:00 INFO 16592 --- [ restartedMain] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheStatistics,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=initializr.project-resources
2022-12-20T15:01:05.843+01:00 INFO 16592 --- [ restartedMain] org.ehcache.core.EhcacheManager : Cache 'initializr.templates' created in EhcacheManager.
2022-12-20T15:01:05.843+01:00 INFO 16592 --- [ restartedMain] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheConfiguration,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=initializr.templates
2022-12-20T15:01:05.844+01:00 INFO 16592 --- [ restartedMain] org.ehcache.jsr107.Eh107CacheManager : Registering Ehcache MBean javax.cache:type=CacheStatistics,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=initializr.templates
2022-12-20T15:01:06.026+01:00 INFO 16592 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-12-20T15:01:06.031+01:00 INFO 16592 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2022-12-20T15:01:06.078+01:00 INFO 16592 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-12-20T15:01:06.089+01:00 INFO 16592 --- [ restartedMain] io.spring.start.site.StartApplication : Started StartApplication in 3.056 seconds (process running for 3.444)
2022-12-20T15:01:17.890+01:00 INFO 16592 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-12-20T15:01:17.891+01:00 INFO 16592 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-12-20T15:01:17.892+01:00 INFO 16592 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2022-12-20T15:01:18.122+01:00 INFO 16592 --- [io-8080-exec-10] .s.SaganInitializrMetadataUpdateStrategy : Fetching Spring Boot metadata from https://spring.io/project_metadata/spring-boot
If I now call http://localhost:8080/ - it works, I didn't do absolutely nothing.
Could it maybe be your JDK? I mean the JDKs are similar but not the same... And you also asked:
I wonder if this effort makes sense. If I manage to build the
application, will I be able of generating code or does the application
connect to somewhere else to retrieve the data required to generate
the code? I would appreciate any hints. Thanks
I personally think, it could make sense but - as soon as I generated a project on my own Spring Initializr, I watched the console of the Spring Boot Application and could see the following log:
Fetching Spring Boot metadata from https://spring.io/project_metadata/spring-boot
So it looks, like this thing actually fetches data from the internet, now I don't know what options you have but I have two in mind.
You could try to fork the GitHub Project and try to remove this network call (if this is really the only one) - I couldn't see anything more in the logs atleast... The actual response of the Call looks pretty simple though:
{"id":"spring-boot","name":"Spring Boot","projectReleases":[{"version":"3.0.1-SNAPSHOT","versionDisplayName":"3.0.1-SNAPSHOT","current":false,"releaseStatus":"SNAPSHOT","snapshot":true},{"version":"3.0.0","versionDisplayName":"3.0.0","current":true,"releaseStatus":"GENERAL_AVAILABILITY","snapshot":false},{"version":"2.7.7-SNAPSHOT","versionDisplayName":"2.7.7-SNAPSHOT","current":false,"releaseStatus":"SNAPSHOT","snapshot":true},{"version":"2.7.6","versionDisplayName":"2.7.6","current":false,"releaseStatus":"GENERAL_AVAILABILITY","snapshot":false},{"version":"2.6.14","versionDisplayName":"2.6.14","current":false,"releaseStatus":"GENERAL_AVAILABILITY","snapshot":false},{"version":"2.5.14","versionDisplayName":"2.5.14","current":false,"releaseStatus":"GENERAL_AVAILABILITY","snapshot":false},{"version":"2.4.13","versionDisplayName":"2.4.13","current":false,"releaseStatus":"GENERAL_AVAILABILITY","snapshot":false}]}
You allow explicitly the URL https://spring.io/project_metadata/spring-boot to fetch data inside of your Air Gap Network (I don't know if this is viable though)
I hope this helps a bit?
There are many dependencies that start from the initializer for spring-boot. If you try to build within an air-gapped network, you will not have access to maven's repository for the dependencies. Try building the package outside the network, and capture the libraries required. Look to your ~/.m2/ folder for the copies of the libraries needed. I would recommend setting up a Nexus repository, and it will capture the libraries as you need them from an open network which you can then use on the air-gapped network.
If this is a secured network, you'll have to have all those files vetted and scanned before you can get them into the air-gapped network. Plan for this.
As you add additional annotations or dependencies, you will have to get them from maven central again. It's not ideal, but you might find someone who setup a project to include all spring-boot dependencies for just this situation.
Also, use the STS dev environment, and build your spring-boot to run with included libraries.

Using UCANACCESS with Spring Boot

I am setting up a very basic Spring-Boot application, to serve some Access database content as a REST service.
After doing battle with getting the ucanaccess jar included in my classpath, now I'm having trouble getting it to connect to my access db.
My spring.datasource is set like this:
spring.datasource.jdbc-url=jdbc:ucanaccess://C:\\Users\\Owner\\Documents\\brigette.accdb;showSchema=true;memory=false
spring.datasource.dialect=net.ucanaccess.hibernate.dialect.UCanAccessDialect
The error I am getting is:
2020-04-08 09:01:28.534 INFO 20740 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-04-08 09:01:28.557 WARN 20740 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata : Failed to get driver instance for jdbcUrl=jdbc:ucanaccess://C:\Users\Owner\Documents\brigette.accdb;showSchema=true;memory=false
2020-04-08 09:01:28.563 WARN 20740 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [agency/newmeta/jsis/BackendDbConfig.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
2020-04-08 09:01:28.568 INFO 20740 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
The access database does exist in that location, but I do get the same error if I use a non-existant db.
HHH000342: Could not obtain connection to query metadata : Failed to get driver instance for jdbcUrl=jdbc:ucanaccess://C:\Users\Owner\Documents\lalala.accdb;showSchema=true;memory=false
and also if I use / instead of delimited :
HHH000342: Could not obtain connection to query metadata : Failed to get driver instance for jdbcUrl=jdbc:ucanaccess://C:/Users/Owner/Documents/brigette.accdb;showSchema=true;memory=false
What I am missing about setting up the conneciton string?
TIA
Brigette
I suggest you to use another approach: use spring jpa with hibernate.
And follow the article:
Accessing MS Access with Hibernate 5 and Spring Boot
At the end of the day it will guide you to implement a little app to read and update an accdb database.
The important thing to point out is the "patch" included in the source code that must be used in your code (without it , your app will never work).
The "patch" is the hibernate dialect: it is very important, it is reported in the source code of the article and shared at the end of the article.

Spring Boot Application issue with rabbitmq in docker

I am trying to build a event driven microservice with spring cloud stream using rabbitmq. In my case, rabbitmq is running in docker.
Docker commands used to run below container
docker run -d --hostname my-rabbit --name some-rabbit --publish 15672:15672 rabbitmq:3
Then going to bash mode of container I fired below command:
rabbitmq-plugins enable rabbitmq_management
in order to start management-plugin
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b2bc315c44aa rabbitmq:3 "docker-entrypoint..." 7 minutes ago Up 7 minutes 4369/tcp, 5671-5672/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp some-rabbit
So I can access docker from browser on localhost:15672
But when I start the Spring Boot application it is not making queue and exchange. Please check the stack trace.
Stack-trace
o.s.i.codec.kryo.CompositeKryoRegistrar : configured Kryo registration [40, java.io.File] with serializer org.springframework.integration.codec.kryo.FileSerializer
o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'rabbitConnectionFactory' has been autodetected for JMX exposure
o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'integrationMbeanExporter' has been autodetected for JMX exposure
o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'integrationMbeanExporter': registering with JMX server as MBean [org.springframework.integration.monitor:name=integrationMbeanExporter,type=IntegrationMBeanExporter]
o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'rabbitConnectionFactory': registering with JMX server as MBean [org.springframework.amqp.rabbit.connection:name=rabbitConnectionFactory,type=CachingConnectionFactory]
o.s.i.monitor.IntegrationMBeanExporter : Registering beans for JMX exposure on startup
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 : Registering MessageChannel output
o.s.i.monitor.IntegrationMBeanExporter : Located managed bean 'org.springframework.integration:type=MessageChannel,name=output': registering with JMX server as MBean [org.springframework.integration:type=MessageChannel,name=output]
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 MessageHandler errorLogger
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
r.t.b.demo.source.GatewayApplication : No active profile set, falling back to default profiles: default
s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#56cfe111: startup date [Mon May 29 15:07:40 JST 2017]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4fe767f3
o.s.c.support.GenericApplicationContext : Refreshing org.springframework.context.support.GenericApplicationContext#67de7a99: startup date [Mon May 29 15:07:40 JST 2017]; root of context hierarchy
r.t.b.demo.source.GatewayApplication : Started GatewayApplication in 0.189 seconds (JVM running for 10.957)
o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare exchange: Exchange [name=output, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused
o.s.integration.channel.DirectChannel : Channel 'gateway:8181.output' has 1 subscriber(s).
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 'gateway:8181.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.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8181 (http)
Thanks in advance.
You need to use the Docker image for RabbitMQ that has the management plugin (see https://hub.docker.com/_/rabbitmq/), in your case rabbitmq:3-management.
I have been wrestling with using rabbit mq running in docker and I think you will need to make some entries in your spring boot application.properties file to overcome the connection problem.
It looks like your exchange is not being created due to connection refused. You need to overcome that. In the rabbit web admin console you will need to create a user with permissions. Then add some configuration in application.properties :
spring.rabbitmq.port=5672
spring.rabbitmq.username=the_user_name
spring.rabbitmq.password=user_password
Good luck.

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