When my springboot application startup, I have the following exception. I didn't found where is problem, if someone has an idea... thanks by advance
2015-05-18 14:50:49,313 DEBUG c.q.q.Application:50 - Running with Spring Boot v1.2.3.RELEASE, Spring v4.1.6.RELEASE
2015-05-18 14:50:51,848 DEBUG o.j.logging:33 - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
2015-05-18 14:50:51,991 DEBUG c.q.q.c.AsyncConfiguration:36 - Creating Async Task Executor
2015-05-18 14:50:52,126 INFO c.q.q.Application:60 - Running with Spring profile(s) : [dev]
2015-05-18 14:50:52,752 DEBUG c.q.q.c.MetricsConfiguration:71 - Registring JVM gauges
2015-05-18 14:50:54,870 ERROR o.s.b.c.e.t.TomcatStarter:62 - Error starting Tomcat context: org.springframework.beans.factory.BeanCreationException
2015-05-18 14:50:54,914 WARN o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext:487 - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at com.qwam.qes.Application.main(Application.java:84) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418) [spring-boot-maven-plugin-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]
Caused by: org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:98) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:75) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:378) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:155) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
... 11 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setAuthenticationConfiguration(org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration.setGlobalAuthenticationConfigurers(java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootAuthenticationConfigurerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/security/AuthenticationManagerConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.boot.autoconfigure.security.SecurityProperties]: : Error creating bean with name 'securityProperties': Could not bind properties to [unknown] (target=security, ignoreInvalidFields=false, ignoreUnknownFields=false, ignoreNestedProperties=false); nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'token[key]' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Cannot access indexed value in property referenced in indexed property path 'token[key]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'token[key]' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Bean property 'token[key]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityProperties': Could not bind properties to [unknown] (target=security, ignoreInvalidFields=false, ignoreUnknownFields=false, ignoreNestedProperties=false); nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'token[key]' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Cannot access indexed value in property referenced in indexed property path 'token[key]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'token[key]' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Bean property 'token[key]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
this is my application class:
#ComponentScan (basePackages = { "com.test" })
#EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
#Domain(basePackages = { "com.test.domain" })
public class Application {
private final Logger log = LoggerFactory.getLogger(Application.class);
#Inject
private Environment env;
#PostConstruct
public void initApplication() throws IOException {
if (env.getActiveProfiles().length == 0) {
log.warn("No Spring profile configured, running with default configuration");
} else {
log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
}
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
// Check if the selected profile has been set as argument.
// if not the development profile will be added
addDefaultProfile(app, source);
}
/**
* Set a default profile if it has not been set
*
* #param app
* #param source
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active")) {
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
}
}
/**
*
* #return
*/
#Bean
public HttpMessageConverter<String> responseBodyConverter() {
return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}
#Bean
public Filter characterEncodingFilter() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return characterEncodingFilter;
}
/**
*
* #return
*/
#Bean
public BeanNameAutoProxyCreator lazyInitAutoProxyCreator() {
BeanNameAutoProxyCreator autoProxyCreator = new BeanNameAutoProxyCreator();
TargetSourceCreator[] targetSourceCreators = {lazyInitTargetSourceCreator()};
autoProxyCreator.setCustomTargetSourceCreators(targetSourceCreators);
return autoProxyCreator;
}
#Bean
public LazyInitTargetSourceCreator lazyInitTargetSourceCreator() {
return new LazyInitTargetSourceCreator();
}
}
Try to add the #Configuration annotation to your Application class
#Configuration
#ComponentScan (basePackages = { "com.test" })
#EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
#Domain(basePackages = { "com.test.domain" })
public class Application {
//some code
}
Related
I'm facing the issue with spring MVC and Hibernate. The problem is, it gives me org.springframework.beans.factory.UnsatisfiedDependencyException.
Here is the error:
18-Apr-2022 00:36:22.172 SEVERE [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.ContextLoader.initWebApplicationContext Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerController' defined in file [D:\Coding\Java\Spring_Framework\zzz\target\zzz\WEB-INF\classes\com\bai\controller\CustomerController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerServiceImpl': Unsatisfied dependency expressed through field 'customerDao'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerDaoImpl' defined in file [D:\Coding\Java\Spring_Framework\zzz\target\zzz\WEB-INF\classes\com\bai\dao\CustomerDaoImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.bai.config.HibernateConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:787)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4761)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5232)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1775)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:291)
at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:814)
at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:802)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:483)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:431)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:291)
at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:814)
at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:802)
at java.management/com.sun.jmx.remote.security.MBeanServerAccessController.invoke(MBeanServerAccessController.java:472)
at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1472)
at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1310)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:712)
at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1412)
at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:360)
at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:712)
at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:587)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:705)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:704)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerServiceImpl': Unsatisfied dependency expressed through field 'customerDao'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerDaoImpl' defined in file [D:\Coding\Java\Spring_Framework\zzz\target\zzz\WEB-INF\classes\com\bai\dao\CustomerDaoImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.bai.config.HibernateConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:397)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1429)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:874)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:778)
... 61 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerDaoImpl' defined in file [D:\Coding\Java\Spring_Framework\zzz\target\zzz\WEB-INF\classes\com\bai\dao\CustomerDaoImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.bai.config.HibernateConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:787)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:636)
... 75 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.bai.config.HibernateConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:645)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:625)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:874)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:778)
... 88 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:640)
... 102 more
Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:87)
at org.springframework.orm.hibernate5.LocalSessionFactoryBuilder.<init>(LocalSessionFactoryBuilder.java:145)
at org.springframework.orm.hibernate5.LocalSessionFactoryBuilder.<init>(LocalSessionFactoryBuilder.java:124)
at com.bai.config.HibernateConfig.getSessionFactory(HibernateConfig.java:30)
at com.bai.config.HibernateConfig$$EnhancerBySpringCGLIB$$89956522.CGLIB$getSessionFactory$2(<generated>)
at com.bai.config.HibernateConfig$$EnhancerBySpringCGLIB$$89956522$$FastClassBySpringCGLIB$$6324619c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at com.bai.config.HibernateConfig$$EnhancerBySpringCGLIB$$89956522.getSessionFactory(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 103 more
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1420)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1228)
... 118 more
18-Apr-2022 00:36:22.187 SEVERE [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
18-Apr-2022 00:36:22.276 SEVERE [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
[2022-04-18 12:36:22,315] Artifact zzz:war exploded: Error during artifact deployment. See server log for details.
18-Apr-2022 00:36:26.406 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [D:\Coding\Java\apache-tomcat-8.5.78\webapps\manager]
18-Apr-2022 00:36:26.480 FINE [localhost-startStop-1] org.apache.jasper.servlet.JasperInitializer.onStartup Initializing Jasper for context [Tomcat Manager Application]
18-Apr-2022 00:36:26.496 FINE [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanResourcePaths No TLD files were found in resource path [/WEB-INF/jsp/].
18-Apr-2022 00:36:26.496 FINE [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanResourcePaths No TLD files were found in resource path [/WEB-INF/].
18-Apr-2022 00:36:26.524 FINE [localhost-startStop-1] org.apache.jasper.compiler.JspRuntimeContext.<init> Parent class loader is: [ParallelWebappClassLoader
context: manager
delegate: false
----------> Parent Classloader:
java.net.URLClassLoader#52f759d7
]
18-Apr-2022 00:36:26.524 FINE [localhost-startStop-1] org.apache.jasper.compiler.JspRuntimeContext.initClassPath Compilation classpath initialized: C:\Users\baistan.tashkuov\AppData\Local\JetBrains\IntelliJIdea2021.3\tomcat\0c7cc667-c02e-4913-aa73-958d11878231\work\Catalina\localhost\manager;/D:/Coding/Java/apache-tomcat-8.5.78/lib/;/D:/Coding/Java/apache-tomcat-8.5.78/lib/annotations-api.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/catalina-ant.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/catalina-ha.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/catalina-storeconfig.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/catalina-tribes.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/catalina.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/ecj-4.6.3.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/el-api.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/jasper-el.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/jasper.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/jaspic-api.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/jsp-api.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/servlet-api.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-api.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-coyote.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-dbcp.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-i18n-de.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-i18n-es.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-i18n-fr.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-i18n-ja.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-i18n-ko.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-i18n-ru.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-i18n-zh-CN.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-jdbc.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-jni.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-util-scan.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-util.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/tomcat-websocket.jar;/D:/Coding/Java/apache-tomcat-8.5.78/lib/websocket-api.jar;D:\Coding\Java\apache-tomcat-8.5.78\bin\bootstrap.jar;D:\Coding\Java\apache-tomcat-8.5.78\bin\tomcat-juli.jar
18-Apr-2022 00:36:26.532 FINE [localhost-startStop-1] org.apache.jasper.servlet.JspServlet.init Scratch dir for the JSP engine is: [C:\Users\baistan.tashkuov\AppData\Local\JetBrains\IntelliJIdea2021.3\tomcat\0c7cc667-c02e-4913-aa73-958d11878231\work\Catalina\localhost\manager]
18-Apr-2022 00:36:26.533 FINE [localhost-startStop-1] org.apache.jasper.servlet.JspServlet.init IMPORTANT: Do not modify the generated servlets
18-Apr-2022 00:36:26.539 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [D:\Coding\Java\apache-tomcat-8.5.78\webapps\manager] has finished in [133] ms
My hibernate config file:
package com.bai.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#ComponentScan(basePackages={"com.bai"})
#EnableTransactionManagement
#PropertySource(value = {"classpath:db.properties"})
public class HibernateConfig {
#Autowired
private Environment env;
#Bean
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
builder.addProperties(getHibernateProperties());
builder.scanPackages("com.bai.entity");
return builder.buildSessionFactory();
}
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
return properties;
}
#Bean
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
App Init Config
package com.bai.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MvcWebApplicationInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { HibernateConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Controller Class
package com.bai.controller;
import com.bai.services.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/customers")
public class CustomerController {
final
CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
#GetMapping()
private String showCustomers(Model model) {
return "views/index";
}
}
Service Implemenation
package com.bai.services;
import com.bai.dao.CustomerDao;
import com.bai.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class CustomerServiceImpl implements CustomerService {
final CustomerDao customerDao;
public CustomerServiceImpl(CustomerDao customerDao) {
this.customerDao = customerDao;
}
#Override
public List<Customer> list() {
List<Customer> list = customerDao.getCustomers();
return list;
}
}
DAO implementation
package com.bai.dao;
import com.bai.entity.Customer;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
#Repository
public class CustomerDaoImpl implements CustomerDao{
final SessionFactory sessionFactory;
public CustomerDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Transactional
#Override
public List<Customer> getCustomers() {
List<Customer> list = null;
try {
list = new ArrayList<Customer>();
Query<Customer> query = sessionFactory.getCurrentSession().createQuery("from Custom");
list = query.getResultList();
} catch (HibernateException e) {
e.printStackTrace();
}
return list;
}
}
How can I fix this?
Accorading to your error log, the root cause is
java.lang.ClassNotFoundException: javax.xml.bind.JAXBException.
Just add the following dependency to pom.xml.
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
I'm struggling to load my configuration in my simple SpringBootApplication. When I attempt to print out the variables in my configuratrion class, they are always null.
Initially I had my configurable variables in WatchApplication.java. However, all of the variables I thought would be read from configuration were still null. The configuration was at /main/resources/application.properties. I've since added a class just to hold the configuration that I plan to read in WatchApplication called WatchConfiguration.
I'm new to Spring and am feeling terminally stupid
The Structure of my classes is:
-main
|--java
| |--WatchApplication.java
| |--WatchConfiguration.java
|
|--resources
|--application.properties
Here's WatchApplication.java
#SpringBootApplication
public class WatchApplication {
private WatchConfiguration configuration;
public static void main(String[] args)
{
SpringApplication.run(WatchApplication.class, args);
}
/**
* Initialize the application
*/
#PostConstruct
public void initialize()
{
configuration = new WatchConfiguration();
System.out.println(configuration.getVideoDirectory());
}
}
Here is what my WatchConfiguration.java looks like
#Configuration
public class WatchConfiguration {
#Value("${video.output.directory}")
private String videoDirectory;
#Value("${target.sites}")
private List<String> targetSites;
public WatchConfiguration getWatchConfiguration ()
{
return new WatchConfiguration();
}
public String getVideoDirectory() {
return videoDirectory;
}
public void setVideoDirectory(String videoDirectory) {
this.videoDirectory = videoDirectory;
}
public List<String> getTargetSites() {
return targetSites;
}
public void setTargetSites(List<String> targetSites) {
this.targetSites = targetSites;
}
}
And my application.properties
video.output.directory = C:\\Users\\Alex\\Desktop\\output
# Target Sites
target.sites[0] = https://youtube.com
target.sites[1] = https://bing.com
Here is the output. Note the 'null' in the console that is supposed to be the video.output.directory property value.
[2019-09-04 20:09:00.752] - 16812 INFO [restartedMain] --- com.pirate.baywatch.BaywatchApplication: Starting BaywatchApplication on DESKTOP-ULP9VBQ with PID 16812 (C:\Users\Alex\IdeaProjects\baywatch\target\classes started by Alex in C:\Users\Alex\IdeaProjects\baywatch)
[2019-09-04 20:09:00.765] - 16812 INFO [restartedMain] --- com.pirate.baywatch.BaywatchApplication: No active profile set, falling back to default profiles: default
[2019-09-04 20:09:00.792] - 16812 INFO [restartedMain] --- org.springframework.boot.devtools.env.DevToolsPropertyDefaultsPostProcessor: Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
null
[2019-09-04 20:09:01.142] - 16812 WARNING [restartedMain] --- org.springframework.context.annotation.AnnotationConfigApplicationContext: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baywatchConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'target.sites' in value "${target.sites}"
[2019-09-04 20:09:01.148] - 16812 INFO [restartedMain] --- org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2019-09-04 20:09:01.154] - 16812 SEVERE [restartedMain] --- org.springframework.boot.SpringApplication: Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baywatchConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'target.sites' in value "${target.sites}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:380)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:743)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:390)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1214)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1203)
at com.pirate.baywatch.BaywatchApplication.main(BaywatchApplication.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'target.sites' in value "${target.sites}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:237)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:211)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:851)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1192)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
... 21 more
Solution
Solved by adding #Autowired to the member variable and removing the initialization of the configuration class from the initialize method
#SpringBootApplication
public class WatchApplication {
#Autowired
private WatchConfiguration configuration;
public static void main(String[] args)
{
SpringApplication.run(WatchApplication.class, args);
}
/**
* Initialize the application
*/
#PostConstruct
public void initialize()
{
System.out.println(configuration.getVideoDirectory());
}
}
The problem is that you are creating configuration by yourself, with new. You should #Autowired it from context in to your application class.
Remove this line configuration = new Watch Configuration and add #Autowired to definition of configuration. I would also suggest you to use configuration properties instead.
These are the beans I have created and trying to use Hikari in my project but getting the errors.
LocalContainerEntityManagerFactoryBean Configuration method:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.xyz.entitiy" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
DataSource configuration method:
#Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig(); config.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource");
config.setDriverClassName("org.postgresql.Driver");
config.setJdbcUrl("jdbc:postgresql://localhost:5432/abc");
config.setUsername("abc");
config.setPassword("abc");
return new HikariDataSource(config);
}
PlatformTransactionManager configuration method:
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
PersistenceExceptionTranslationPostProcessor configuration method:
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
Properties configuration method:
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
return properties;
}
I'm trying to migrate from BoneCP to HikariCP for PostgreSQL. But facing this issue:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.xyz.ets.persistence.config.PersistenceContext: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in com.xyz.ets.persistence.config.PersistenceContext: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in com.xyz.ets.persistence.config.PersistenceContext: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
Caused by: java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
Sep 25, 2018 12:47:28 AM org.apache.catalina.core.StandardContext loadOnStartup
pom.file dependency using:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc41</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.1</version>
</dependency>
spring configuration: Trying to instantiate a JmsMessageListenerContainerFactory Bean that will use a specific connection factory bean instance using annotations.
#Configuration
public class DemoJmsConfig {
#Value("${jms.context.factory}")
private String initialContextFactory;
#Value("${jms.provider.url}")
String jmsProviderUrl;
//Inbound
#Value("${jms.inbound.qcf.userName}")
private String inboundQcfUserName;
#Value("${jms.inbound.qcf.password}")
private String inboundQcfPassword;
#Value("${jms.inbound.queue.connectionfactory}")
private String inboundQueueConnectionFactory;
#Value("${jms.inbound.queue.name}")
private String inboundQueueName;
#Value("${jms.inbound.initial.cache.size}")
private String inboundInitCacheSize;
//Outbound
#Value("${jms.outbound.topic.connectionfactory}")
private String outboundTopicConnectionFactory;
#Value("${jms.outbound.topic.name}")
private String outboundTopicName;
#Value("${jms.outbound.tcf.userName}")
private String outboundTcfUserName;
#Value("${jms.outbound.tcf.password}")
private String outboundTcfPassword;
#Value("${jms.outbound.initial.cache.size}")
private String outboundInitCacheSize;
#Bean
public InitialContext initialContext() throws NamingException {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,
initialContextFactory);
props.put(Context.PROVIDER_URL, jmsProviderUrl);
// Create the initial context from the properties we just created
return new InitialContext(props);
}
#Bean(name="inboundConnectionFactory")
#Qualifier("inboundConnectionFactory")
public ConnectionFactory inboundConnectionFactory() throws NamingException {
//Create a Connection Factory adapter with user credentials
UserCredentialsConnectionFactoryAdapter uccfa = new UserCredentialsConnectionFactoryAdapter();
ConnectionFactory cf = (ConnectionFactory) initialContext().lookup(inboundQueueConnectionFactory);
uccfa.setTargetConnectionFactory(cf);
uccfa.setUsername(inboundQcfUserName);
uccfa.setPassword(inboundQcfPassword);
CachingConnectionFactory ccf = new CachingConnectionFactory();
if(inboundInitCacheSize != null && Integer.parseInt(inboundInitCacheSize) > 0){
ccf.setSessionCacheSize(Integer.parseInt(inboundInitCacheSize)); //Default is 1
}
ccf.setTargetConnectionFactory(uccfa);
return ccf;
}
#Bean(name="inboundJMSTemplate")
#Qualifier("inboundJMSTemplate")
public JmsTemplate inboundJMSTemplate(#Qualifier("inboundConnectionFactory") ConnectionFactory inboundConnectionFactory ) throws NamingException{
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(inboundConnectionFactory);
jmsTemplate.setDefaultDestinationName(inboundQueueName);
return jmsTemplate;
}
#Bean(name="inboundJmsListenerContainerFactory")
#Qualifier("inboundJmsListenerContainerFactory")
public JmsListenerContainerFactory<?> inboundJmsListenerContainerFactory(
DefaultJmsListenerContainerFactoryConfigurer configurer,
#Qualifier("inboundConnectionFactory") ConnectionFactory inboundConnectionFactory)
throws NamingException {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
// This provides all boot's default to this factory, including the
// message converter
configurer.configure(factory, inboundConnectionFactory);
// You could still override some of Boot's default if necessary.
return factory;
}
#Bean(name="outboundConnectionFactory")
#Qualifier("outboundConnectionFactory")
public ConnectionFactory outboundConnectionFactory() throws NamingException {
//Create a Connection Factory adapter with user credentials
UserCredentialsConnectionFactoryAdapter uccfa = new UserCredentialsConnectionFactoryAdapter();
ConnectionFactory cf = (ConnectionFactory) initialContext().lookup(outboundTopicConnectionFactory);
uccfa.setTargetConnectionFactory(cf);
uccfa.setUsername(outboundTcfUserName);
uccfa.setPassword(outboundTcfPassword);
CachingConnectionFactory ccf = new CachingConnectionFactory();
if(outboundInitCacheSize != null && Integer.parseInt(outboundInitCacheSize) > 0){
ccf.setSessionCacheSize(Integer.parseInt(outboundInitCacheSize)); //Default is 1
}
ccf.setTargetConnectionFactory(uccfa);
return ccf;
}
#Bean(name="outboundErrorJMSTemplate")
#Qualifier("outboundErrorJMSTemplate")
public JmsTemplate outboundErrorJMSTemplate(#Qualifier("outboundConnectionFactory") ConnectionFactory outboundConnectionFactory ) throws NamingException{
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(outboundConnectionFactory);
jmsTemplate.setDefaultDestinationName(outboundTopicName);
return jmsTemplate;
}
}
Expected result: The JmsListenerContainerFactory is instantiated.
Actual:
*************************** APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of method jmsListenerContainerFactory in org.springframework.boot.autoconfigure.jms.JmsAnnotationDrivenConfiguration required a single bean, but 2 were found:
- inboundConnectionFactory: defined by method 'inboundConnectionFactory' in class path resource [com/example/demo/config/DemoJmsConfig.class]
- outboundConnectionFactory: defined by method 'outboundConnectionFactory' in class path resource [com/example/demo/config/DemoJmsConfig.class]
Action:
Consider marking one of the beans as #Primary, updating the consumer to accept multiple beans, or using #Qualifier to identify the bean that should be consumed
[WARNING] java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jmsListenerContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.class]: Unsatisfied dependency expressed through method 'jmsListenerContainerFactory' parameter 1; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.jms.ConnectionFactory' available: expected single matching bean but found 2: inboundConnectionFactory,outboundConnectionFactory at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) at com.example.demo.DemoApplication.main(DemoApplication.java:10) ... 6 more Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.jms.ConnectionFactory' available: expected single matching bean but found 2: inboundConnectionFactory,outboundConnectionFactory at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ... 25 more
I have tried specifying qualifiers, bean names.. still getting errors. Can anyone suggest what I should do to resolve this. I need both the inbound and outbound connections since the application will consume and publish
resolved by adding #Primary to inbound Connection factory
Check this question Spring Boot multiple JMS connections that can help you. If in your case are using a mix of Spring XML and annotations to make a connection factory, maybe you can have problems with SpringBoot, in this case thy disable autostart of spring-boot-jms with this in your application:
#SpringBootApplication(exclude = {JmsAutoConfiguration.class})
this was my case.
I'm having a problem with my testing. I'm using java spring and trying to run junit test to check if my server is alive.
This the test I'm trying:
#RunWith(SpringJUnit4ClassRunner::class)
#ContextConfiguration(classes = arrayOf(ServiceContext::class,DatabaseContext::class))
#Transactional
open class newtest : AbstractTestController(){
#Test
fun echoTest() {
mockMvc.perform(get("/echo").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk)
}
}
This is the AbstractTestController class that my newtest class is extending:
#WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {
#Autowired
lateinit var webAppContext: WebApplicationContext
lateinit var mockMvc: MockMvc
#Autowired
lateinit var authHelper: OAuthHelper
#Autowired
private lateinit var userService: UserService
fun adminToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.adminAuthorities.toTypedArray())
fun clientItToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.clientItAuthorities.toTypedArray())
fun clientManagerToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.clientManagerAuthorities.toTypedArray())
fun endUserToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.endUserAuthorities.toTypedArray())
#Autowired
lateinit var mapper: ObjectMapper
fun <T> ResultActions.and200ReturnClass(clazz: TypeReference<T>): ResultActions {
if (this.andReturn().response.status == HttpServletResponse.SC_OK
&& this.andReturn().response.contentAsString.isNotEmpty()) {
mapper.readValue<T>(this.andReturn().response.contentAsString, clazz)!!
}
return this
}
#Before
fun initialize() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webAppContext)
.apply<DefaultMockMvcBuilder>(SecurityMockMvcConfigurers.springSecurity())
.alwaysDo<DefaultMockMvcBuilder>(MockMvcResultHandlers.print())
.build()
}
}
My configuration:
#Configuration
#Import(value = *arrayOf(
OAuth2ServerConfiguration::class,
OAuth2ServerConfiguration.AuthorizationServerConfiguration::class,
OAuth2ServerConfiguration.ResourceServerConfiguration::class,
SecurityConfig::class,
OAuthHelper::class,
WebConfig::class,
DatabaseInitializator::class,
LowerCaser::class))
#ComponentScan("com.hyg","com.hyg.service", "com.hyg.web", "com.hyg.utils")
#EnableAutoConfiguration
#EnableAspectJAutoProxy(proxyTargetClass = true)
open class ServiceContext
#Configuration
#EnableJpaRepositories("com.hyg")
#EnableTransactionManagement
#EnableAutoConfiguration
#PropertySource("classpath:application.properties")
open class DatabaseContext {
val DATA_PACKAGE = "com.hyg.data"
val INTERCEPTOR_KEY = "hibernate.ejb.interceptor"
#Value("\${spring.datasource.username:${Const.NONE}}")
lateinit var username: String
#Value("\${spring.datasource.url}")
lateinit var url: String
#Value("\${spring.datasource.driverClassName}")
lateinit var driverClass: String
#Value("\${spring.datasource.password}")
lateinit var password: String
#Bean
#Primary
open fun objectMapper(): ObjectMapper {
val mapper = ObjectMapper()
mapper.registerModule(KotlinModule())
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
mapper.configure(MapperFeature.USE_STD_BEAN_NAMING, true)
mapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false)
mapper.registerModule(JavaTimeModule())
mapper.registerModule(localDateTimeSerializer())
return mapper
}
#Bean
open fun localDateTimeSerializer(): SimpleModule {
val localDateTimeSerializer = SimpleModule()
val serializer = LocalDateTimeSerializer(
DateTimeFormatter.ofPattern(Const.DATE_TIME_PATTERN))
val deserializer = LocalDateTimeDeserializer(
DateTimeFormatter.ofPattern(Const.DATE_TIME_PATTERN))
localDateTimeSerializer.addSerializer(LocalDateTime::class.java, serializer)
localDateTimeSerializer.addDeserializer(LocalDateTime::class.java, deserializer)
return localDateTimeSerializer
}
#Bean
open fun dataSource(): DataSource {
val ds = DataSourceBuilder.create().driverClassName(driverClass).username(username).password(password).url(url).build()
val proxy = ProxyDataSource()
proxy.setDataSource(ds)
proxy.setListener(DataSourceQueryCountListener())
return proxy
}
#Bean
open fun entityManagerFactory(
factory: EntityManagerFactoryBuilder, dataSource: DataSource,
properties: JpaProperties): LocalContainerEntityManagerFactoryBean {
val jpaProperties = HashMap<String, Any>()
jpaProperties.putAll(properties.getHibernateProperties(dataSource))
jpaProperties.put(INTERCEPTOR_KEY, hibernateInterceptor())
return factory.dataSource(dataSource).packages(DATA_PACKAGE)
.properties(jpaProperties as MutableMap<String, *>)
.build()
}
#Bean
open fun hibernateInterceptor(): HibernateStatisticsInterceptor {
return HibernateStatisticsInterceptor()
}
#Bean
open fun requestStatisticsInterceptor(): RequestStatisticsInterceptor {
return RequestStatisticsInterceptor()
}
}
This is the full Error I'm getting:
2017-11-17 20:03:52.477 WARN --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
2017-11-17 20:03:52.477 INFO --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-11-17 20:03:52.499 INFO --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-11-17 20:03:52.508 ERROR --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener#6b19b79] to prepare test instance [com.hyginex.Integration.newtest#7a08da83]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1056)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:134)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:61)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 24 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
... 41 common frames omitted
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:172)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1114)
at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.getIfAvailable(DefaultListableBeanFactory.java:1643)
at org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration.<init>(EndpointMBeanExportAutoConfiguration.java:63)
at org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa.<init>(<generated>)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 43 common frames omitted
Hope it will help to solve my problem.
I tried so far to put #Primary on the Bean that make the ObjectMapper or to add those annotation #Order
#ConditionalOnMissingBean but it didn't work...
Thank you
You have several beans with the type ObjectMapper in the Spring Context. Try to add the annotation #Qualifier("objectMapper") for mapper (in AbstractTestController) or rename it to objectMapper:
#WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {
...
#Qualifier("objectMapper")
#Autowired
lateinit var mapper: ObjectMapper
...
}
or
#WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {
...
#Autowired
lateinit var objectMapper: ObjectMapper
...
}