Exception while building a war file via (maven install) for a spring boot project with mongodb - mongodb

I am trying to build a spring-boot application with mongodb. I excluded the spring-boot-starter-data-mongodb dependency and using mongodb-driver 3.12.5.
My application.properties file contains only spring.data.mongodb.uri=connection _string.
With this above configuration I am unable to build a war file to deploy in server. It is giving the following error.
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.NoClassDefFoundError: com/mongodb/connection/DefaultClusterFactory
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.NoClassDefFoundError: com/mongodb/connection/DefaultClusterFactory
Caused by: java.lang.NoClassDefFoundError: com/mongodb/connection/DefaultClusterFactory
Caused by: java.lang.ClassNotFoundException: com.mongodb.connection.DefaultClusterFactory
please help, thanks.

This is issue was solved by replacing the mongodb-driver dependency with mongodb-java-driver dependency
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.6.3</version>
</dependency>
as for the situation i faced i did not add a dependency that i am using in the application. that was the mistake.

Related

SpringBoot: Cannot load driver class: org.postgresql.Driver

I have just created a new SpringBoot application (Java11) and am trying to connect to a Postgres database.
When I start the SpringBoot application, there is an error trying to connect to the database. The error reports that it Cannot load driver class: org.postgresql.Driver.
Question
How do I change my configuration below to get the SpringBoot application to connect to the database?
database version
PostgreSQL 12.6 on x86_64-apple-darwin16.7.0, compiled by Apple LLVM
version 8.1.0 (clang-802.0.42), 64-bit
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
application.properties
# pims datasource
spring.datasource.url=jdbc:postgresql://localhost:5432/pims
spring.datasource.username=postgres
spring.datasource.password=
spring.datasource.driverClassName=org.postgresql.Driver
#spring.datasource.driver-class-name=org.postgresql.Driver
#spring.jpa.database-platform=postgres
spring.jpa.show-sql=true
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.validation-query=select 1
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
When I run the #SpringBootApplication class, SpringBoot starts to start up as expected, but gets the following error.
error
Error starting ApplicationContext. To display the conditions report
re-run your application with 'debug' enabled. 2021-06-15 11:58:51.770
ERROR 68967 --- [ main] o.s.boot.SpringApplication
: Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'dataSourceScriptDatabaseInitializer'
defined in class path resource
[org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]:
Unsatisfied dependency expressed through method
'dataSourceScriptDatabaseInitializer' parameter 0; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalStateException: Cannot load driver class:
org.postgresql.Driver
If I remove the following entry (i.e. don't define the driver in application.properties and just have the pom dependency):
spring.datasource.driverClassName=org.postgresql.Driver
I then get the following error:
Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader
When I expend the external dependency tree, I didn't find any jar for postgressql. After reimport maven dependency, it is added correctly and problem is gone. It is fine now.
You do not need any specific configuration to connect database unless your repository and entity packages are not pulled from another dependency.
I would suggest you to check your connection between your computer and maven repository. You should be missing your postgre dependecy somehow.
(You also would try providing specific version of postgresql artifact)

springboot rest swagger :error in initialising bean

I am using swagger to document my spring boot rest application
Using
spring-boot-starter-web
spring-boot-starter-data-rest
springfox-swagger2 2.9.2
springfox-swagger 2.9.2
Code is building fine but when I run it it is throwing error below
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration
$EnableWebMvcConfiguration.class]:
Unsatisfied dependency expressed through method 'requestMappingHandlerMapping' parameter 1;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration
$EnableWebMvcConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.format.support.FormattingConversionService]:
Factory method 'mvcConversionService' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'jsonSchemaConverter' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.rest.webmvc.json.PersistentEntityToJsonSchemaConverter]:
Factory method 'jsonSchemaConverter' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'defaultConversionService' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.format.support.DefaultFormattingConversionService]:
Factory method 'defaultConversionService' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'repositoryInvokerFactory' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.repository.support.RepositoryInvokerFactory]:
Factory method 'repositoryInvokerFactory' threw exception;
nested exception is java.lang.NoSuchMethodError: org.springframework.plugin.core.PluginRegistry.of(Ljava/util/List;)Lorg/springframework/plugin/core/PluginRegistry;
I had the same problem. Here is my fix:
TL/DR:
Springfox uses an outdated version of spring-plugin-core and is incompatible with spring boot 2.2.5. Springfox seems to be no longer maintained; migrate to a different spring-swagger-bridge, such as Springdoc-openapi: https://springdoc.github.io/springdoc-openapi-demos/
Relevant output
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.repository.support.RepositoryInvokerFactory]:
Factory method 'repositoryInvokerFactory' threw exception; nested exception is java.lang.NoSuchMethodError:
'org.springframework.plugin.core.PluginRegistry org.springframework.plugin.core.PluginRegistry.of(java.util.List)'
From NoSuchMethodError: org.springframework.plugin.core.PluginRegistry.getPluginOrDefaultFor:
...a wild guess would be that the last working version of springfox (working for you and us) was compiled with a Spring boot version inferior to 2.2.2. That boot version had a different method signature for getPluginOrDefaultFor (or possibly the method didn't exist at all).
Cause
springfox imports version 1.2.0 of the spring-plugin-core. Spring Boot 2.2.5 needs version 2.0.0.RELEASE
springfox wins the import lottery; test fails b/c Spring Boot can't find its method.
explicitly importing 2.0.0.RELEASE makes springfox die.
springfox' latest version is 2.9.2; even the 3.0.0-SNAPSHOT does not fix the issue: https://github.com/springfox/springfox/issues/2932
Solution
Springfox is apparently abandoned:
Springfox swagger not working in spring boot 2.2.0
Solution is to migrate to a different spring-swagger bridge.
Most likely candidate is Springdoc-openapi:
https://springdoc.github.io/springdoc-openapi-demos/
User experience (last comment from https://github.com/springfox/springfox/issues/2932):
Yes I ended up following the links to 'springDoc' and found a
quick tutorial.
It was super easy to setup all in the pom.xml file.
Just one tweak was needed
<!-- org.springdoc for swagger setup -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-core</artifactId>
<version>1.1.49</version>
<exclusions>
<exclusion>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.1.49</version>
</dependency>

JHipster registry : build error

I try to build and run jhipster registry, but I get an error :
mvn package -Pprod
I get following errors in test :
Tests in error:
SwaggerBasePathRewritingFilterTest.<init>:20 » Unresolved compilation problem...
SwaggerBasePathRewritingFilterTest.<init>:20 » Unresolved compilation problem...
SwaggerBasePathRewritingFilterTest.<init>:20 » Unresolved compilation problem...
SwaggerBasePathRewritingFilterTest.<init>:20 » Unresolved compilation problem...
AccountResourceTest.setup:33 » NoClassDefFound HttpServletRequest
AccountResourceTest.setup:33 » NoClassDefFound HttpServletRequest
AccountResourceTest.setup:33 » NoClassDefFound HttpServletRequest
AccountResourceTest.setup:33 » NoClassDefFound HttpServletRequest
UserJWTControllerTest.setup:39 » NoClassDefFound HttpServletResponse
UserJWTControllerTest.setup:39 » NoClassDefFound HttpServletResponse
UserJWTControllerTest.setup:39 » NoClassDefFound HttpServletResponse
ExceptionTranslatorTest.setup:37 » NoClassDefFound HttpServletRequest
ExceptionTranslatorTest.setup:37 » NoClassDefFound HttpServletRequest
ExceptionTranslatorTest.setup:37 » NoClassDefFound HttpServletRequest
ExceptionTranslatorTest.setup:37 » NoClassDefFound HttpServletRequest
ExceptionTranslatorTest.setup:37 » NoClassDefFound HttpServletRequest
If I skip tests, build is ok, but I got same error when I launch :
./mvnw -Pdev
2018-02-16 17:52:22.011 WARN 5354 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webConfigurer' defined in file [/home/denis/ngworkspace/jhipster-registry/target/classes/io/github/jhipster/registry/config/WebConfigurer.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.github.jhipster.registry.config.WebConfigurer$$EnhancerBySpringCGLIB$$a8d0938a]: Constructor threw exception; nested exception is java.lang.Error: Unresolved compilation problems:
The import io.undertow.UndertowOptions cannot be resolved
ServletContext cannot be resolved to a type
ServletException cannot be resolved to a type
DispatcherType cannot be resolved to a type
DispatcherType cannot be resolved to a variable
DispatcherType cannot be resolved to a variable
DispatcherType cannot be resolved to a variable
The type io.undertow.Undertow$Builder cannot be resolved. It is indirectly referenced from required .class files
This lambda expression refers to the missing type Undertow$Builder
UndertowOptions cannot be resolved to a variable
ServletContext cannot be resolved to a type
DispatcherType cannot be resolved to a type
FilterRegistration cannot be resolved to a type
ServletContext cannot be resolved to a type
DispatcherType cannot be resolved to a type
FilterRegistration cannot be resolved to a type
ServletRegistration cannot be resolved to a type
2018-02-16 17:52:22.032 ERROR 5354 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webConfigurer' defined in file [/home/denis/ngworkspace/jhipster-registry/target/classes/io/github/jhipster/registry/config/WebConfigurer.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.github.jhipster.registry.config.WebConfigurer$$EnhancerBySpringCGLIB$$a8d0938a]: Constructor threw exception; nested exception is java.lang.Error: Unresolved compilation problems:
The import io.undertow.UndertowOptions cannot be resolved
ServletContext cannot be resolved to a type
ServletException cannot be resolved to a type
...
Strangely, when I execute
mvn clean package -Pprod
build is ok, but it does not launch (same error).
I use registry in version 3.2.4, cloned from github, on Linux.
How build registry without error ? Do I forget something ?
Thanks, Denis
I found the solution. I added these dependencies in pom.xml :
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
<scope>provided</scope>
</dependency>
and all work. These dependencies were nevertheless obtained transitively, and I don't known why I have to add explicitly. Anybody has the response ?
Denis
If you were running with Eclipse:
in Eclipse select Project Properties->Maven->Active Maven Profiles (comma separated), and make it dev
That triggers a maven update of the project and everything compiles
No need to put dependencies in the pom
Do that is work
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
<scope>provided</scope>
</dependency>
#Atatorus

java.lang.ClassNotFoundException: org.eclipse.osgi.framework.internal.core.BundleHost

After moving to the osgi version org.eclipse.osgi_3.10.1.v20140909-1633.jar,the following exception is thrown
java.lang.ClassNotFoundException: org.eclipse.osgi.framework.internal.core.BundleHost
I use this class to check if a bundle is instance of BundleHost.

Running JUnit Test cases for Maven Project in Eclipse

I imported Maven project using maven eclipse plugins (m2e) and everything is fine.
But when I am running JUnit Test cases, I am getting below errors
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'be.belgacom.rosy.betty.manager.impl.ReservationManagerImplTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests.setDataSource(javax.sql.DataSource); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
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:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests.setDataSource(javax.sql.DataSource); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:589)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:547)
... 28 more
I am sure you might be suggesting to look at properties and other xml files configurations are correct or not.
If I import the same project into Eclipse as normal project, I am able to run the JUnit tests.
When I Import as Maven Projects, it's giving such errors.
Any idea, how do i solve this.
Your question lacks a lot of context. Have you ever run this from the command line with Maven? For example, have you run "mvn test" on the command line? Try this first then let us know if you receive the same error messages.
Your problem suggests that your POM doesn't contain the appropriate dependencies.