Getting a ClassNotFound exception when using mongotemplate - java

I am getting the following exception when running a spring boot application that uses the mongo template:
Caused by: java.lang.ClassNotFoundException: org.springframework.data.mongodb.MongoDatabaseFactory
This is the main code:
package com.example.redismongo.mongodb;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.MongoTemplate;
#Configuration
#EnableMongoAuditing
public class MongoConfiguration {
#Bean
public MongoClient mongo(){
return MongoClients.create("mongodb://localhost:27017");
}
#Primary
#Bean(name = "mongoTemplate")
public MongoTemplate mongoTemplate(){
return new MongoTemplate(mongo(), "test");
}
}
plugins {
id 'org.springframework.boot' version '2.4.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation group: 'org.springframework.data', name: 'spring-data-commons', version: '2.2.8.RELEASE'
implementation group: 'org.springframework.data', name: 'spring-data-mongodb', version: '2.2.8.RELEASE'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
I need to test the 2.2.8 version as that is the version that is being used at work. I am trying to test some of its functionality in my pc to test certain fail scenarios. How can I make 2.2.8 work?

Try adding spring-boot-starter-data-mongodb instead of spring-data-mongodb.

Related

Caused by: java.lang.ClassNotFoundException: DemoApplication

I created a new Spring application from https://start.srping.io
My build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.5'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '19'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
tasks.named('test') {
useJUnitPlatform()
}
File DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
I press button Run, the program error. How to fix it?
Looks like project dependencies mentioned in build.gradle file not downloaded properly because I can see some compilation errors as well.
Please run this command and try again.
gradle build

Aws Lambda with Spring Boot and Gradle not working. Class not found exception when AWS Lambda function is called

I am using Spring Boot 2.4.8 and I have created sample demo for Aws Lambda. I am using build tool gradle. So When I was deployed my jar on Aws Lambda then I received class not found exception.
for reference please see the attach screen shot.
Following is my build.gradle file
plugins {
id 'org.springframework.boot' version '2.4.8'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'com.h2database:h2'
implementation 'org.springframework.cloud:spring-cloud-function-adapter-aws:2.0.1.RELEASE'
implementation 'com.amazonaws:aws-lambda-java-core:1.2.1'
implementation 'com.amazonaws:aws-lambda-java-events:2.2.9'
implementation 'com.google.code.gson:gson:2.8.6'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
On Aws Lambda I have configured following value in the handler.
com.example.handler.NotificationHandler:handleRequest
Following is my package structure.
NotificationHandler.java file
package com.example.handler;
import java.util.HashMap;
import org.springframework.stereotype.Component;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
#Component
public class NotificationHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
#Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
response.setIsBase64Encoded(false);
response.setStatusCode(200);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
response.setHeaders(headers);
response.setBody("{\n"
+ " \"key1\": \"value1\",\n"
+ " \"key2\": \"value2\",\n"
+ " \"key3\": \"value3\"\n"
+ "}");
// log execution details
Util.logEnvironment(event, context, gson);
return response;
}
}
Any help or suggestion is more help to me.
The Lambda developer guide specifies specific packaging instructions for Gradle
task buildZip(type: Zip) {
from compileJava
from processResources
into('lib') {
from configurations.runtimeClasspath
}
}

Why am I getting 404 status on running a simple spring boot gradle project?

I am new to spring-boot. I have created a simple spring-boot version 2.2.6 project with gradle build. I have created a welcome jsp just to print a header. I get 404 status when i run it on my server with http://localhost:8081/welcome.html Following is my build.gradle, application class, controller class and application.properties file:
//build.gradle
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.banuprojects'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
implementation 'javax.servlet:jstl'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
//application class
package com.banuprojects.lmsdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LmsdemoApplication {
public static void main(String[] args) {
SpringApplication.run(LmsdemoApplication.class, args);
}
}
//controller class
package com.banuprojects.lmsdemo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TestController {
#RequestMapping("/welcome.html")
public ModelAndView firstPage() {
return new ModelAndView("welcome");
}
}
//application.properties
spring.mvc.view.prefix:/WEB-INF/jsp/
spring.mvc.view.suffix:.jsp
I am not sure where I have one wrong with the implementation. Any help will be appreciated.
Thank you
As discussed over the comments. After seeing the application properties file, found that wrong port was passed in the URL.
No other technical error found.

Java Integration Test No Runnable Methods error - Spring Runner

I am trying to write my first integration test. JUnit tests are working fine.
Here is my WebControllerIT.java which is the corresponding integration test for my WebController class:
package com.socialinteraction.componenttests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.socialinteraction.SocialInteractionApplication;
import com.socialinteraction.WebController;
import com.socialinteraction.database.repositories.AppUserRepository;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
#RunWith(SpringRunner.class)
#SpringBootTest(
classes = SocialInteractionApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebControllerIT {
#LocalServerPort private int webServerPort;
#Autowired private AppUserRepository AppUserRepository;
#Autowired private WebController webController;
private RestTemplate restTemplate = new RestTemplate();
private String createURLWithPort(String uri) {
return "http://localhost:" + webServerPort + uri;
}
#Test
public void testSetNewAppUser() {
assertTrue(true);
assertTrue(false);
}
}
I am trying to troubleshoot why my Integration Test is not working, hence the simple assertTrue() methods.
I am currently getting a java.lang.Exception: No runnable methods, when I try and run the test class, that test method of the new integrationTest Gradle task I created.
Here is my package structure for context:
Lastly, here is my build.gradle file:
plugins {
id 'org.springframework.boot' version '2.2.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.socialinteraction'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
integrationTestCompile.extendsFrom testCompile
integrationTestRuntime.extendsFrom testRuntime
integrationTestImplementation.extendsFrom testImplementation
}
repositories {
mavenCentral()
}
sourceSets {
integrationTest {
java {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
srcDir file('src/integration-test/java')
}
resources.srcDir file('src/integration-test/resources')
}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation('org.junit.jupiter:junit-jupiter-api:5.4.2')
testRuntime('org.junit.jupiter:junit-jupiter-engine:5.4.2')
// testCompile "org.powermock:powermock-module-junit4:1.6.4"
// testCompile 'org.mockito:mockito-core:2.7.22'
implementation 'org.jetbrains:annotations:15.0'
implementation 'junit:junit:4.12'
implementation 'org.testng:testng:6.9.6'
implementation 'junit:junit:4.12'
implementation 'junit:junit:4.12'
implementation 'org.testng:testng:6.9.6'
integrationTestCompile 'org.assertj:assertj-core:3.0.0'
}
test {
useJUnitPlatform()
}
task integrationTest(type: Test) {
testClassesDirs = sourceSets.integrationTest.output.classesDirs
classpath = sourceSets.integrationTest.runtimeClasspath
}
check.dependsOn integrationTest
integrationTest.mustRunAfter test
Any ideas why I cannot run my integration tests? Any input would be helpful, thank you!
I'm not sure but probably you are mixing junit4 with junit5. Try using this dependencies:
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.junit.jupiter:junit-jupiter-api'
And remove all junit, assertJ, testing dependencies
Then replace #RunWith(SpringRunner.class) with #ExtendWith(SpringExtension.class)
And classes = SocialInteractionApplication.class is probably not needed in that case.

A component required a bean named 'org.springframework.boot.context.internalConfigurationPropertiesBinder' that could not be found

I have a spring boot multi-module project with Gradle. While running the application i am getting the below error:-
Description:
A component required a bean named 'org.springframework.boot.context.internalConfigurationPropertiesBinder' that could not be found.
Action:
Consider defining a bean named 'org.springframework.boot.context.internalConfigurationPropertiesBinder' in your configuration.
The project has a root project which has a subproject 'GetAssociationService'
rootproject - build.gradle
plugins {
id 'org.springframework.boot' version '2.2.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id 'com.github.johnrengelman.shadow' version '5.2.0'
}
bootJar { enabled = false }
jar { enabled = true }
subprojects {
group = 'org.qmetech'
version = '1.0.0'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'java'
}
repositories { mavenCentral ( ) }
ext { set ( 'springCloudVersion' , "Hoxton.SR3" ) }
dependencies {
testImplementation ( 'org.springframework.boot:spring-boot-starter-test' ) {
exclude group: 'org.junit.vintage' , module: 'junit-vintage-engine'
}
}
ext.libraries = [
commonlibraries: [ 'org.springframework.boot:spring-boot-starter:2.2.5.RELEASE' ,
'org.springframework.cloud:spring-cloud-function-context' ,
'org.springframework.cloud:spring-cloud-function-adapter-aws:2.0.1.RELEASE' ,
'com.amazonaws:aws-lambda-java-log4j:1.0.0' ,
'org.springframework.boot:spring-boot-starter-web:2.2.5.RELEASE' ,
'org.springframework.cloud:spring-cloud-starter-function-web:1.0.0.RELEASE' ,
'org.springframework.boot.experimental:spring-boot-thin-layout:1.0.11.RELEASE' ,
'org.springframework.boot:spring-boot-starter-data-mongodb:2.2.5.RELEASE',
'org.springframework.cloud:spring-cloud-function-compiler:2.0.0.RELEASE'] ,
]
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
test { useJUnitPlatform ( ) }
ChildProject - build.gradle
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
springBoot {
mainClassName = 'org.qmetech.GetAssociationService'
}
dependencies {
dependencies {
compile libraries.commonlibraries
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
}
}
UserRepository.java
package org.qmetech.repository;
import org.qmetech.domain.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends MongoRepository<User, Integer> { }
AssociationService.java
package org.qmetech.service;
import org.qmetech.domain.User;
import org.qmetech.repository.UserRepository;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.function.Function;
#Component
public class AssociationService implements Function<String, List<User>> {
private final UserRepository userRepository;
public AssociationService(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public List<User> apply(String uppercaseRequest) {
List<User> users = userRepository.findAll();
return users;
}
}
The Complete Code can be found here - https://github.com/iftekharkhan09/Services
Can Anyone please tell me what am I doing wrong?
Thanks!
I also had this problem and in my case, there was the problem in 'org.springframework.boot' version. I changed my version to 2.1.6 Release. Then the problem resolved.
Please verify your pom.xml and make sure you are using the matching version of the Spring boot framework for Spring Cloud.
e.g. For Spring Cloud Greenwich you will need Spring boot 2.1.x
Here is Spring cloud documentation : https://spring.io/projects/spring-cloud
Revisit section : Release Trains

Categories

Resources