spring.jmx.enabled property always set to true - spring

Now, I have a problem about setting a property named spring.jmx.enabled
While upgrading the spring version from 2.2.7 to 2.7.0, we found the following error.
ERROR 2022-09-17 23:27:06 [main] o.s.boot.SpringApplication [tid=] - Application run failed
org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [HikariDataSource (some-service-write)] with key 'writeDataSource'; nested exception is javax.management.InstanceAlreadyExistsException: MXBean already registered with name com.zaxxer.hikari:type=PoolConfig (some-service-write)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:626)
at org.springframework.jmx.export.MBeanExporter.lambda$registerBeans$2(MBeanExporter.java:552)
at java.util.HashMap.forEach(HashMap.java:1289)
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:552)
at org.springframework.jmx.export.MBeanExporter.afterSingletonsInstantiated(MBeanExporter.java:435)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:972)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
at com.company.team.name.some.SomeServiceApplication.main(SomeServiceApplication.java:16)
Caused by: javax.management.InstanceAlreadyExistsException: MXBean already registered with name com.zaxxer.hikari:type=PoolConfig (some-service-write)
at com.sun.jmx.mbeanserver.MXBeanLookup.addReference(MXBeanLookup.java:151)
at com.sun.jmx.mbeanserver.MXBeanSupport.register(MXBeanSupport.java:160)
at com.sun.jmx.mbeanserver.MBeanSupport.preRegister2(MBeanSupport.java:173)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:930)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:138)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:672)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:616)
... 14 common frames omitted
I searched for this error, and most of them answered that can be solved by setting spring.jmx.enabled to false.
However, I checked that the error continues to occur even if the property corrects this value.
Debugging, this value was coming to true.
I injected properties into the Vm Option like -Dspring.jmx.enabled=false, but I confirmed that the same result came.
How can I set this value to false?

if you define in application.propertiers:
spring.datasource.hikari.registerMbeans=true
you have to disable the default Mbean with this config
#Bean
public MBeanExporter exporter() {
final MBeanExporter exporter = new AnnotationMBeanExporter();
exporter.setAutodetect(true);
exporter.setExcludedBeans("dataSource");
return exporter;
}
for more details : https://github.com/brettwooldridge/HikariCP/issues/342

Make sure you do not have #EnableMBeanExport on your application configuration. It can override the external property.
Learn more about this annotation here: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/EnableMBeanExport.html

You can try changing the default registration policy as below, it will ignore existing bean.
#Configuration
#EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class MXBeansConfig {
}

Related

Migration to Spring 6

I am trying to migrate to Spring 6 and I am getting stuck with following error:
Class org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider does not implement the requested interface jakarta.persistence.spi.PersistenceProvider
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:376) ~[spring-orm-6.0.2.jar:6.0.2]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-6.0.2.jar:6.0.2]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-6.0.2.jar:6.0.2]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:352) ~[spring-orm-6.0.2.jar:6.0.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1797) ~[spring-beans-6.0.2.jar:6.0.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1747) ~[spring-beans-6.0.2.jar:6.0.2]
... 58 more
I checked and SpringHibernateJpaPersistenceProvider implements org.hibernate.jpa.HibernatePersistenceProvider which certainly implements jakarta.persistence.spi.PersistenceProvider.
I checked and there does not seem to be other versions on the classpath and also from the stacktrace you can see ~[spring-orm-6.0.2.jar:6.0.2] which means the current version should be correctly used. Where can I search for the error?
This was caused by propagated dependency through c3p0:
implementation("org.hibernate:hibernate-core-jakarta:5.6.14.Final")
implementation("org.hibernate:hibernate-c3p0:5.6.14.Final") {
// propagates unwanted hibernate-core module
exclude(group = "org.hibernate", module = "hibernate-core")
}

Unable to start eureka sever using sping cloud config server

I am working on a micro service based on spring boot
Now i have two services
configserver
discoveryserver
coreservice
I can able to start configserver and coreserver.Both are working fine.coreserver taking configuration from configserver. All properties are save on my file system as an application properties
configurations
when i run my discoveryserver it showing below error
20:52:34.918 [main] ERROR org.springframework.boot.SpringApplication - Application run failed
java.lang.IllegalStateException: Unable to load config data from 'configserver:'
at org.springframework.boot.context.config.StandardConfigDataLocationResolver.getReferences(StandardConfigDataLocationResolver.java:141)
at org.springframework.boot.context.config.StandardConfigDataLocationResolver.getReferences(StandardConfigDataLocationResolver.java:126)
at org.springframework.boot.context.config.StandardConfigDataLocationResolver.resolve(StandardConfigDataLocationResolver.java:119)
at org.springframework.boot.context.config.ConfigDataLocationResolvers.lambda$resolve$1(ConfigDataLocationResolvers.java:115)
at org.springframework.boot.context.config.ConfigDataLocationResolvers.resolve(ConfigDataLocationResolvers.java:126)
at org.springframework.boot.context.config.ConfigDataLocationResolvers.resolve(ConfigDataLocationResolvers.java:115)
at org.springframework.boot.context.config.ConfigDataLocationResolvers.resolve(ConfigDataLocationResolvers.java:107)
at org.springframework.boot.context.config.ConfigDataImporter.resolve(ConfigDataImporter.java:105)
at org.springframework.boot.context.config.ConfigDataImporter.resolve(ConfigDataImporter.java:97)
at org.springframework.boot.context.config.ConfigDataImporter.resolveAndLoad(ConfigDataImporter.java:85)
at org.springframework.boot.context.config.ConfigDataEnvironmentContributors.withProcessedImports(ConfigDataEnvironmentContributors.java:116)
at org.springframework.boot.context.config.ConfigDataEnvironment.processInitial(ConfigDataEnvironment.java:240)
at org.springframework.boot.context.config.ConfigDataEnvironment.processAndApply(ConfigDataEnvironment.java:227)
at org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor.postProcessEnvironment(ConfigDataEnvironmentPostProcessor.java:102)
at org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor.postProcessEnvironment(ConfigDataEnvironmentPostProcessor.java:94)
at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEnvironmentPreparedEvent(EnvironmentPostProcessorApplicationListener.java:102)
at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEvent(EnvironmentPostProcessorApplicationListener.java:87)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:85)
at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:66)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:120)
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:114)
at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:65)
at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:344)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:302)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
at com.nielsen.discoveryserver.DiscoveryServerApplication.main(DiscoveryServerApplication.java:12)
Caused by: java.lang.IllegalStateException: File extension is not known to any PropertySourceLoader. If the location is meant to reference a directory, it must end in '/' or File.separator
at org.springframework.boot.context.config.StandardConfigDataLocationResolver.getReferencesForFile(StandardConfigDataLocationResolver.java:229)
at org.springframework.boot.context.config.StandardConfigDataLocationResolver.getReferences(StandardConfigDataLocationResolver.java:138)
... 31 common frames omitted
Process finished with exit code 1
discovery server application.properties
spring.cloud.config.uri= http://localhost:8888
spring.application.name = discoveryserver
spring.config.import = configserver:
spring.profiles.active= native
configuration repository properties named same as application name
discoveryserver.properties
server.port =8081
mian class
#SpringBootApplication
#EnableEurekaServer
public class DiscoveryServerApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryServerApplication.class, args);
}
}
coreserver have the similar configurations.its working file for me.i coudn't understand why discoveryserver throwing error.
Help on this issue.
Thanks in advance.

Spring Boot compatibility issues when upgrading to new libraries

I am in the process of upgrading a Spring Boot application to support Micrometer and Actuator monitoring. I have upgraded the Spring libraries to newer versions, and I have refactored the code accordingly (you can see before and after code samples later in in this question). I could run the application successfully before; when I try to do so now, I am getting the following error message:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-08-20 14:14:59.302 ERROR 29703 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:163) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577) ~[spring-context-5.3.9.jar:5.3.9]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:143) [spring-boot-2.5.3.jar:2.5.3]
at com.openbet.realitycheck.Application.main(Application.java:22) [classes/:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:210) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:160) ~[spring-boot-2.5.3.jar:2.5.3]
... 7 common frames omitted
The below screenshot describes the library versions that were previously used:
enter image description here
These are the upgraded libraries that I am using now:
enter image description here
Some before-and-after code samples:
Before:
#SpringApplicationConfiguration(classes = {Application.class, IntegrationTestConfiguration.class})
#WebIntegrationTest("server.port=0")
After:
#SpringBootTest(classes = {Application.class, IntegrationTestConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
Before:
#SpringApplicationConfiguration(classes = UnitTestConfiguration.class)
After:
#SpringBootTest(classes = UnitTestConfiguration.class)
Here is my starter class:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
// Change the default config name to xxxxxxxxxxxx.
new SpringApplicationBuilder(Application.class)
.properties(Collections.singletonMap("spring.config.name", "xxxxxxxxxxxx"))
.run(args);
}
}
When I specify that this is not a Web Application...
#SpringBootApplication
public class Application {
public static void main(String[] args) {
// Change the default config name to xxxxxxxxxxxx.
new SpringApplicationBuilder(Application.class)
.web(WebApplicationType.NONE)
.properties(Collections.singletonMap("spring.config.name", "xxxxxxxxxxxx"))
.run(args);
}
}
...I receive a different set of error messages:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field customerPrefRepository in com.corpname.appname.core.services.CustomerPrefServiceImpl required a bean of type 'com.corpname.appname.core.repositories.CustomerPrefRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.corpname.appname.core.repositories.CustomerPrefRepository' in your configuration.
As this is a web-based application, I don't know of how much use this last bit for information would be.

Wildfly / Infinispan HTTP session replication hits ClassNotFoundException when unmarshalling CGLIB Session Bean

I'm running Wildfly 20.0.1.Final in standalone, two-node cluster. I'm trying to implement HTTP Session sharing between the nodes.
In my Spring web application I have <distributable/> in my web.xml.
My session object is this:
package my.package;
#Component
#Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.INTERFACES)
public class MySessionBean implements Serializable {
// omitted for brevity
}
As you can see, I have ScopedProxyMode.TARGET_CLASS.
When I perform a failover in Wildfly, my HTTP Session can't be restored however, as I hit this warning:
2021-02-22 13:24:18,651 WARN [org.wildfly.clustering.web.infinispan] (default task-1) WFLYCLWEBINF0007:
Failed to activate attributes of session Pd9oI0OBiZSC9we0uXsZdBwkLnadO1l4TUfvoJZf:
org.wildfly.clustering.marshalling.spi.InvalidSerializedFormException:
java.lang.ClassNotFoundException: my.package.MySessionBean$$EnhancerBySpringCGLIB$$9c0fa1df
from [Module "deployment.myDeployment.war" from Service Module Loader]
...
Caused by: java.lang.ClassNotFoundException: my.package.MySessionBean$$EnhancerBySpringCGLIB$$9c0fa1df from [Module "deployment.myDeployment.war" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:255)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at org.jboss.marshalling#2.0.9.Final//org.jboss.marshalling.ModularClassResolver.resolveClass(ModularClassResolver.java:133)
at org.jboss.marshalling.river#2.0.9.Final//org.jboss.marshalling.river.RiverUnmarshaller.doReadClassDescriptor(RiverUnmarshaller.java:1033)
at org.jboss.marshalling.river#2.0.9.Final//org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1366)
at org.jboss.marshalling.river#2.0.9.Final//org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:283)
at org.jboss.marshalling.river#2.0.9.Final//org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:216)
at org.jboss.marshalling#2.0.9.Final//org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:41)
at org.wildfly.clustering.marshalling.spi#20.0.1.Final//org.wildfly.clustering.marshalling.spi.util.MapExternalizer.readObject(MapExternalizer.java:65)
...
Note, that the ClassNotFoundException is complaining because the lack of my.package.MySessionBean$$EnhancerBySpringCGLIB$$9c0fa1df, which is the Spring-enhanced bean of my MySessionBean bean.
Changing to ScopedProxyMode.INTERFACES is not an option.
Can you please point me in the right direction with this?
I managed to fix this by creating a simple POJO, called MySessionDTO, and using that in my session.
So initially I had this (which threw the exception in the question):
request.getSession().setAttribute("mySession", mySessionBean);
...and after I created MySessionDTO (see below), I refactored it into this:
request.getSession().setAttribute("mySession", mySessionBean.getMySessionDTO());
MySessionDTO is a simple POJO:
package my.package;
import java.io.Serializable;
public class MySessionDTO extends MySessionBean implements Serializable {
public MySessionDTO (MySessionBean mySessionBean) {
this.setAttributeX(mySessionBean.getAttributeX());
this.setAttributeY(mySessionBean.getAttributeY());
}
}

Spring Integration beans aren't created when spring.main.lazy-initialization=true

With reference to my earlier question here
Spring Boot app fails to start when all beans are marked as Lazy, as it can't find an error channel
and a reference to the issue here:
https://github.com/spring-projects/spring-boot/issues/16184#issuecomment-480196051
does anyone know what beans need to be added to an instance of LazyInitializationExcludeFilter in order for Spring Integration to start when spring.main.lazy-initialization=true ?
I'm getting errors like below, saying that "myErrorChannel" bean isn't available, where this is defined in code like so:
#MessagingGateway(errorChannel = "myErrorChannel")
#FunctionalInterface
public interface SomeInterface{
}
How can I make the creation of the error channel eager rather than lazy ? Adding a LazyInitializationExcludeFilter and trying to filter out beans called "myErrorChannel" doesn't work, as there must be another (lazy) bean that isn't creating the errorChannel bean.
Stacktrace:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myErrorChannel' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:805)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1278)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:297)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.integration.support.channel.BeanFactoryChannelResolver.resolveDestination(BeanFactoryChannelResolver.java:89)
at org.springframework.integration.support.channel.BeanFactoryChannelResolver.resolveDestination(BeanFactoryChannelResolver.java:46)
at org.springframework.integration.gateway.MessagingGatewaySupport.getErrorChannel(MessagingGatewaySupport.java:414)
at org.springframework.integration.graph.IntegrationGraphServer$NodeFactory.gatewayNode(IntegrationGraphServer.java:374)
at org.springframework.integration.graph.IntegrationGraphServer.lambda$gateways$5(IntegrationGraphServer.java:258)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet.lambda$entryConsumer$0(Collections.java:1577)
at java.util.HashMap$EntrySpliterator.forEachRemaining(HashMap.java:1699)
at java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntrySetSpliterator.forEachRemaining(Collections.java:1602)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:485)
at org.springframework.integration.graph.IntegrationGraphServer.gateways(IntegrationGraphServer.java:263)
at org.springframework.integration.graph.IntegrationGraphServer.buildGraph(IntegrationGraphServer.java:184)
at org.springframework.integration.graph.IntegrationGraphServer.onApplicationEvent(IntegrationGraphServer.java:115)
at org.springframework.integration.graph.IntegrationGraphServer.onApplicationEvent(IntegrationGraphServer.java:66)
Solved by making any beans that are created in this manner as lazy:
#Bean
public IntegrationFlow someBeanName() {
return IntegrationFlows.from("someString")
.handle(restCallFailedHandler())
.handle(finishedHandler())
.get();
}

Resources