My springBoot project can't autowire his services with the repositories - java

As i said in the title i have a springboot project and i'm trying to run it, but when i try to start a clean install using maven i get an error during the test :
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 5.805 s <<< FAILURE! - in ---myprojectpath---
contextLoads Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myController': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'myRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'myRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
if i ignore this error during the build of mavyour texten i still get a different error when i try tu run my app, i hope that resolving this error ill' be finally able to solve everything.
Anyways here is a part of my controller:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/Mycontroller")
public class Mycontroller{
private static final Logger LOGGER = LoggerFactory.getLogger(Mycontroller.class);
ObjectMapper mapper = new ObjectMapper();
#Autowired
private MyService MyService ;
#GetMapping(value = "/getDatas", produces = "application/json")
public ResponseEntity getDatas() {
try {
DataList responseEntity = new DataList ();
List<Data> datas= MyService.getDatasBean();
..........
} catch (Exception e) {
..........
}
}
}
here is my service:
public interface MyService {
List<Data> getDatasBean() throws Exception;
}
here is the implementation of my service
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.NoResultException;
import java.util.List;
#Service
#Transactional(readOnly = false)
public class MyServiceImpl implements MyService{
private static final Logger LOGGER = LoggerFactory.getLogger(MyServiceImpl.class);
#Autowired
private MyRepository MyRepository ;
public List<Data> getDatasBean() throws Exception {
LOGGER.info(String.format("looking for datas"));
try {
return MyRepository.getAllDatas();
} catch (NoResultException e) {
return null;
} catch (IllegalStateException | IllegalArgumentException e) {
throw new Exception(e);
//throw new BackOfficeEntityException(String.format("error"), e);
}
}
}
here is the repository:
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface MyRepository extends CrudRepository<Data, Long> {
#Query("SELECT a " +"FROM Data a ")
List<Data> getAllDatas();
}
as you can read in the log the error is when i bind Myserviceimpl with MyRepository... but i don't understand what i did wrong.... here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven 4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<artifactId>Myproject-jpa</artifactId>
<packaging>jar</packaging>
<name>Myproject-jpa</name>
<dependencies>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.14</version>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>2.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>11</source>
<target>11</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
any help is appreciated, thanks :)
I tried to run the various maven steps (clean,validate,compile,test,package,verify,install) but i got the error that i already pasted, and i tryed to run anyway my application but i get a different error(i think that this last error can be resolvedjust resolving the error that comes up during the test).
i tryed to change the dependencies in the pom.xml but honestly i still don't understand it at all.

No major mistakes in your code. Just use the naming standards(camelCase) properly for your objects. Here is the working code with the proper naming of variables.
MyServiceImpl.java
#Service
#Transactional(readOnly = false)
public class MyServiceImpl implements MyService{
private static final Logger LOGGER = LoggerFactory.getLogger(MyServiceImpl.class);
#Autowired
private MyRepository myRepository ;
public List<Data> getDatasBean() throws Exception {
LOGGER.info(String.format("looking for datas"));
try {
return myRepository.getAllDatas();
} catch (NoResultException e) {
return null;
} catch (IllegalStateException | IllegalArgumentException e) {
throw new Exception(e);
//throw new BackOfficeEntityException(String.format("error"), e);
}
}
}
Mycontroller.java
#RestController
#RequestMapping("/Mycontroller")
public class Mycontroller{
private static final Logger LOGGER = LoggerFactory.getLogger(Mycontroller.class);
ObjectMapper mapper = new ObjectMapper();
#Autowired
private MyService myService ;
#GetMapping(value = "/getDatas", produces = "application/json")
public ResponseEntity getDatas() {
try {
List responseEntity = new ArrayList();
List<Data> datas= myService.getDatasBean();
} catch (Exception e) {
}
..........
}
}

Related

CRUD Testing with Jupiter in spring boots giving error:jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered

Error for test 1 - org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [final com.orrs.authmicro.customer.CustomerService customerService] in constructor [public com.orrs.authmicro.AuthMicroApplicationTests(com.orrs.authmicro.customer.CustomerService,com.orrs.authmicro.customer.CustomerRepository)].
Error for Test 2 -org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [final com.orrs.authmicro.customer.CustomerService customerService] in constructor [public com.orrs.authmicro.AuthMicroApplicationTests(com.orrs.authmicro.customer.CustomerService,com.orrs.authmicro.customer.CustomerRepository)].
I have looked at most of the solutions available and they advice to remove #Test or #ParameterizedTest . My tests are not found if I remove #Test and I cant remove #ParameterizedTest because I'm not using it. I have spent hours already and can't seem to overcome this. Before this there were Bean Creation Errors--- UnsatisfiedDependencyException: Error creating bean with name customerService
Testfile
package com.orrs.authmicro;
import com.orrs.authmicro.customer.*;
import lombok.AllArgsConstructor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
#AllArgsConstructor
#DataJpaTest
class AuthMicroApplicationTests {
#Autowired
private final CustomerService customerService;
private final CustomerRepository customerRepository;
#Test
public void testJpaSave(){
Customer customer = customerRepository.save(new Customer(
"TestFname",
"TestLname",
"TestAddress",
"99999999999",
Gender.MALE,
"TestPassword",
"testEmail#gmail.com",
CustomerRole.USER
));
assertThat(customer.getId()).isGreaterThan(0);
}
#Test
public void testRegistration(){
String response = customerService.signUpCustomer(
new Customer(
"TestFname",
"TestLname",
"TestAddress",
"99999999999",
Gender.MALE,
"TestPassword",
"testEmail#gmail.com",
CustomerRole.USER
)
);
assertThat(response.equals("Signed up perfectly)"));
}
}
CustomerRespository
package com.orrs.authmicro.customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
#Transactional(readOnly = true)
#Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Optional<Customer> findByEmail(String email);
}
CustomerService
package com.orrs.authmicro.customer;
import lombok.AllArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.security.Principal;
import java.util.Optional;
#Service
#AllArgsConstructor
public class CustomerService implements UserDetailsService {
private final BCryptPasswordEncoder bCryptPasswordEncoder;
private final String USER_NOT_FOUND = "Customer with email %s not found";
private final CustomerRepository customerRepository;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return customerRepository.findByEmail(email)
.orElseThrow(()-> new UsernameNotFoundException(String.format(USER_NOT_FOUND,email)));
}
public String signUpCustomer(Customer customer){
boolean customerExists = customerRepository.findByEmail(customer.getEmail())
.isPresent();
if(customerExists){
throw new IllegalStateException("User with Email already exist!");
}
if(customer.getPassword() == ""){
throw new IllegalStateException("Password cannot be empty");
}
if(customer.getFname() == "" || customer.getFname().isEmpty()){
throw new IllegalStateException("Name cannot be empty");
}
if(customer.getGender().equals("")){
throw new IllegalStateException("Gender cannot be empty");
}
if(customer.getAddress().equals("")){
throw new IllegalStateException("Address cannot be empty");
}
String encodedPassword = bCryptPasswordEncoder.encode(customer.getPassword());
customer.setPassword(encodedPassword);
customerRepository.save(customer);
return "Signed up perfectly";
}
public String currentUsername(Principal principal){
return principal.getName();
}
public Customer updateCustomer(Customer customer){
//Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//String userName = currentUsername((Principal) principal);
boolean customerExists = customerRepository.findByEmail(customer.getEmail()).isPresent();
if(customerExists){
Optional<Customer> wrapperCustomer = customerRepository.findByEmail(customer.getEmail());
Customer existingCustomer = wrapperCustomer.get();
existingCustomer.setAddress(customer.getAddress());
existingCustomer.setFname(customer.getFname());
existingCustomer.setLname(customer.getLname());
existingCustomer.setPhoneNumber(customer.getPhoneNumber());
existingCustomer.setGender(customer.getGender());
customerRepository.save(existingCustomer);
return existingCustomer;
}else{
throw new IllegalStateException("User doesn't exist");
}
}
public String deleteCustomerById(String email){
boolean customerExists = customerRepository.findByEmail(email).isPresent();
if(customerExists){
Optional<Customer> wrapperCustomer = customerRepository.findByEmail(email);
Customer existingCustomer = wrapperCustomer.get();
customerRepository.deleteById(existingCustomer.getId());
return "Customer Deleted Successfully!";
}else{
throw new IllegalStateException("User Not Found");
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.orrs</groupId>
<artifactId>auth-micro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>auth-micro</name>
<description>Authorisation microservice</description>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2021.0.3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

Unable to run JUnit5 tests with Maven

I'm running into an issue where I can't run JUnit5 tests using Maven. Running them in the IDE works just fine but using "mvn test" produces the following output:
T E S T S
[INFO] -------------------------------------------------------
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
Here are my test classes :
package com.example.spstream.controllers.events;
import com.example.spstream.entities.Event;
import com.example.spstream.repositories.EventRepository;
import com.example.spstream.repositories.UserRepository;
import com.example.spstream.util.Mapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.time.LocalDateTime;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
#EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
public class EventsCreationTest {
private static final String MISSING_TITLE_ERROR_MESSAGE = "title is missing";
private static final String MISSING_ACTIVITY_ERROR_MESSAGE = "activity is missing";
private static final String MISSING_LOCALISATION_ERROR_MESSAGE = "localisation is missing";
private static final String INVALID_ORGANISER_ID_ERROR_MESSAGE = "user %s does not exist";
private static final String MISSING_ORGANISER_ID_ERROR_MESSAGE = "organiser id is missing";
#Autowired
private MockMvc mockMvc;
#MockBean
private UserRepository userRepository;
#SpyBean
private EventRepository eventRepository;
private static final String DATE_IN_PAST_ERROR_MESSAGE = "date is in the past";
#BeforeEach
public void reset(){
Mockito.reset(userRepository);
Mockito.when(userRepository.existsById("123456")).thenReturn(true);
}
//prevents hardcoded events from failing tests due to date in the past
public void setEventDateToTomorrow(Event event) {
event.setDateTime(LocalDateTime.now().plusDays(1));
}
public void setEventDateToYesterday(Event event) {
event.setDateTime(LocalDateTime.now().minusDays(1));
}
public void testCorrectEventCreationWithEvent(Event event) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/events")
.content(Mapper.writeObjectToJson(event))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").exists())
.andExpect(jsonPath("$.id").isString());
}
public void testIncorrectEventCreationWithEvent(Event event, String errorMessagePattern) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/events")
.content(Mapper.writeObjectToJson(event))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().string(containsString(String.format(errorMessagePattern, event.getOrganiserId()))));
}
/**
* correct data
**/
#Test
public void testMinimalCorrectEvent() throws Exception {
Event minimalEvent = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/correct/minimal_event.json"), Event.class);
setEventDateToTomorrow(minimalEvent);
testCorrectEventCreationWithEvent(minimalEvent);
}
#Test
public void testMaximalCorrectEvent() throws Exception {
Event maximalEvent = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/correct/maximal_event.json"), Event.class);
setEventDateToTomorrow(maximalEvent);
testCorrectEventCreationWithEvent(maximalEvent);
}
/**
* missing data
**/
#Test
public void testIncorrectEventTitleMissing() throws Exception {
Event eventTitleMissing = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/correct/minimal_event.json"), Event.class);
setEventDateToTomorrow(eventTitleMissing);
eventTitleMissing.setTitle(null);
testIncorrectEventCreationWithEvent(eventTitleMissing, MISSING_TITLE_ERROR_MESSAGE);
}
#Test
public void testIncorrectEventActivityMissing() throws Exception {
Event eventActivityMissing = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/correct/minimal_event.json"), Event.class);
eventActivityMissing.setActivity(null);
setEventDateToTomorrow(eventActivityMissing);
testIncorrectEventCreationWithEvent(eventActivityMissing, MISSING_ACTIVITY_ERROR_MESSAGE);
}
#Test
public void testIncorrectEventLocalisationMissing() throws Exception {
Event eventLocalisationMissing = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/correct/minimal_event.json"), Event.class);
eventLocalisationMissing.setLocalisation(null);
setEventDateToTomorrow(eventLocalisationMissing);
testIncorrectEventCreationWithEvent(eventLocalisationMissing, MISSING_LOCALISATION_ERROR_MESSAGE);
}
#Test
public void testIncorrectEventMissingUserId() throws Exception {
Event eventOrganiserIdMissing = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/incorrect/missing_user_id.json"), Event.class);
setEventDateToTomorrow(eventOrganiserIdMissing);
testIncorrectEventCreationWithEvent(eventOrganiserIdMissing, MISSING_ORGANISER_ID_ERROR_MESSAGE);
}
/**
* invalid data
**/
#Test
public void testIncorrectEventInvalidOrganiserId() throws Exception {
Mockito.when(userRepository.existsById(Mockito.any())).thenReturn(false);
Event eventInvalidOrganiserId = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/correct/minimal_event.json"), Event.class);
setEventDateToTomorrow(eventInvalidOrganiserId);
testIncorrectEventCreationWithEvent(eventInvalidOrganiserId, INVALID_ORGANISER_ID_ERROR_MESSAGE);
}
#Test
public void testIncorrectEventDateInThePast() throws Exception {
Event eventInPast = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/correct/minimal_event.json"), Event.class);
setEventDateToYesterday(eventInPast);
testIncorrectEventCreationWithEvent(eventInPast, DATE_IN_PAST_ERROR_MESSAGE);
}
/**
* internal database issue
**/
#Test
public void testCorrectEventServerError() throws Exception {
Event eventInvalidOrganiserId = Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/create/correct/minimal_event.json"), Event.class);
setEventDateToTomorrow(eventInvalidOrganiserId);
Mockito.when(eventRepository.save(eventInvalidOrganiserId)).thenThrow(Mockito.mock(DataAccessException.class));
mockMvc.perform(MockMvcRequestBuilders.post("/events")
.content(Mapper.writeObjectToJson(eventInvalidOrganiserId))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is5xxServerError());
System.out.println("whatever");
}
}
package com.example.spstream.controllers.events;
import com.example.spstream.entities.Event;
import com.example.spstream.repositories.EventRepository;
import com.example.spstream.util.Mapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.List;
import java.util.Optional;
import static com.example.spstream.util.Mapper.readJsonFromFile;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
#EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
public class EventsAccessTest {
#MockBean
EventRepository mockEventRepository;
#Autowired
MockMvc mockMvc;
#BeforeEach
public void reset(){
Mockito.reset(mockEventRepository);
}
#Test
public void testFindAll() throws Exception{
List<Event> events = Mapper.readObjectListFromJson(readJsonFromFile("controllers/events/access/all_events.json"), Event.class);
Mockito.when(mockEventRepository.findAll()).thenReturn(events);
mockMvc.perform(MockMvcRequestBuilders.get("/events")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().json(Mapper.readJsonFromFile("controllers/events/access/all_events.json")));
}
#Test
public void testFindEventWhichExists() throws Exception{
Mockito.when(mockEventRepository.findById("123456")).thenReturn(Optional.of(Mapper.readObjectFromJson(Mapper.readJsonFromFile("controllers/events/access/final_event.json"),Event.class)));
mockMvc.perform(MockMvcRequestBuilders.get("/events/123456")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().json(Mapper.readJsonFromFile("controllers/events/access/final_event.json")));
}
#Test
public void testFindEventWhichDoesntExist() throws Exception {
Mockito.when(mockEventRepository.findById("7891011")).thenReturn(Optional.empty());
mockMvc.perform(MockMvcRequestBuilders.get("/events/7891011")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
#Test
public void testFindEventDatabaseError() throws Exception {
Mockito.when(mockEventRepository.findById("123456")).thenThrow(Mockito.mock(DataAccessException.class));
mockMvc.perform(MockMvcRequestBuilders.get("/events/123456")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is5xxServerError());
}
}
The pom :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spstream</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spstream</name>
<description>spstream</description>
<properties>
<java.version>17</java.version>
<testcontainers.version>1.16.2</testcontainers.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.32.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>${testcontainers.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>3.0.0-M5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
I have done some research and I figured it might have something to do mith mixing up JUnit4 and JUnit5 features which leads to maven surefire plugin not running tests. However I can't find where those leftover JUnit4 features might be.
I'd appreciate any help.
As pointed out by other comments and answers I had residual JUnit4 dependencies due to test containers. I was able to fix the issue by explicitly setting JUnit5 as a dependency for maven surefire plugin like so :
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
</dependency>
</dependencies>
</plugin>
The Junit4 is available because of Testcontainer dependency.
Testcontainers have a dependency on Junit4 and have it available by default.
You might also encounter the following issue in few cases:
IDE's detects the test cases written in Junit4 format but in sometime in case you make the test classes and methods package-private, they don't detect it.
I am not sure if they would be removing it in further releases but they do have Junit5 support which should resolve the issue
https://www.testcontainers.org/test_framework_integration/junit_5/

Spring can't find Service or Repository beans to Autowire

I'm trying to run spring boot with spring data as basically as possible with swing.
However, even though all seems to be properly configured, when I try to run it, I get an error message saying it couldn't find my Service bean.
package db.westworld.dao;
import db.westworld.entities.RobotEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface RobotRepository extends CrudRepository<RobotEntity, Integer> {
}
package db.westworld.service;
import db.westworld.entities.RobotEntity;
import java.util.Optional;
public interface IRobotService {
Optional<RobotEntity> findById(int id);
}
package db.westworld.service;
import db.westworld.dao.RobotRepository;
import db.westworld.entities.RobotEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
#Service
public class RobotService implements IRobotService {
private final RobotRepository robotRepository;
#Autowired
RobotService(RobotRepository robotRepository) {
this.robotRepository = robotRepository;
}
#Override
public Optional<RobotEntity> findById(int id) {
return robotRepository.findById(id);
}
public void saveRobot(RobotEntity robot) {
robotRepository.save(robot);
}
}
package db.westworld;
import db.westworld.view.RegisterRobot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import java.awt.*;
#SpringBootApplication
public class WestworldApplication {
public static void main(String[] args) {
var ctx = new SpringApplicationBuilder(RegisterRobot.class).headless(false).run(args);
EventQueue.invokeLater(() -> {
var ex = ctx.getBean(RegisterRobot.class);
ex.setVisible(true);
});
}
}
package db.westworld.view;
import db.westworld.entities.RobotEntity;
import db.westworld.service.RobotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.swing.*;
import java.awt.event.*;
import java.util.Date;
#Controller
public class RegisterRobot extends JDialog {
private RobotService robotService;
#Autowired
public void setRobotService (RobotService robotService) {
this.robotService = robotService;
}
private void onOK() {
RobotEntity robot = new RobotEntity();
robot.setCreatedAt(new Date());
robot.setId(1);
robotService.saveRobot(robot);
dispose();
}
}
Error message:
Parameter 0 of method setRobotService in db.westworld.view.RegisterRobot required a bean of type 'db.westworld.service.RobotService' that could not be found.
Action:
Consider defining a bean of type 'db.westworld.service.RobotService' in your configuration.
(the JDialog implementation just includes the basics)
The same also happens when I try to autowire the repository.
Also, in case needed, here's my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <groupId>db</groupId>
<artifactId>westworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>westworld</name>
<description>westworldSpringBoot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The parameter to new SpringApplicationBuilder() must be the class annotate with #SpringBootApplication, as shown in every Spring Boot example I've ever seen, e.g. Create an Application class in the "Getting Started - Building an Application with Spring Boot" guide.

Spring boot application is not running due to failure of initialization of 'requestMappingHandlerMapping'

It is a spring boot 2.0.0 application which was running earlier, but this error started after I added dependencies for spring-cloud-stream.I tried removing spring-fox dependency but it only removed the nested exception.
The complete error after removing spring-fox dependency:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
The complete pom.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.foo.bar.application</groupId>
<artifactId>application-reviews-manager</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>generic-name</name>
<description>Manager</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<application.utils.version>1.0.0</application.utils.version>
<application.utils.build.number>SNAPSHOT</application.utils.build.number>
<application.rnr.repositories.version>1.0.0</application.rnr.repositories.version>
<application.rnr.repositories.build.number>SNAPSHOT</application.rnr.repositories.build.number>
<dcp.config.version>0.0.1</dcp.config.version>
<dcp.config.build.number>SNAPSHOT</dcp.config.build.number>
<aspectj.version>1.8.9</aspectj.version>
</properties>
<dependencies>
<dependency>
<groupId>com.foo.bar.application</groupId>
<artifactId>application-rnr-repositories</artifactId>
<version>${application.rnr.repositories.version}-${application.rnr.repositories.build.number}</version>
</dependency>
<dependency>
<groupId>com.foo.bar.application</groupId>
<artifactId>application-utils</artifactId>
<version>${application.utils.version}-${application.utils.build.number}</version>
</dependency>
<dependency>
<groupId>com.foo.dcp.commons.config</groupId>
<artifactId>dcp-config-client</artifactId>
<version>${dcp.config.version}-${dcp.config.build.number}</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>1.58</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch.test</groupId>
<artifactId>framework</artifactId>
<version>5.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
I'm just a starter in spring-cloud-stream, so any help would be appreciated.
Edit:
We found out that the mistake is in the way or place the annotation
#EnableBinding is used.
The relevant pieces of codes are:
Application.java
package com.foo.bar;
import com.foo.bar.configuration.FooStreams;
import com.foo.bar.configuration.BarStreams;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.context.annotation.Bean;
import com.externalpackage.config.client.AppConfiguration;
import com.foo.bar.storage.repository.CustomElasticRestClient;
#SpringBootApplication
#EnableBinding({FooStreams.class, BarStreams.class})
public class FooApplication {
public static void main(String[] args) {
SpringApplication.run(FooApplication.class, args);
}
#Bean
public AppConfiguration appConfiguration() {
return AppConfiguration.instance();
}
#Bean
public CustomElasticRestClient highLevelElasticClient(AppConfiguration appConfiguration) throws Exception {
return new CustomElasticRestClient(appConfiguration);
}
}
FooStreams.java
package com.foo.bar.configuration;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
public interface FooStreams {
String OUTPUT = "foo-out";
#Output(value = OUTPUT)
MessageChannel postFooToOutChanel();
}
BarStreams.java
package com.tesco.foo.bar.configuration;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
public interface BarStreams {
String OUTPUT = "bar-out";
#Output(value = OUTPUT)
MessageChannel postBarToOutChanel();
}
KafkaPublisherService.java:
package com.foo.bar.service;
import com.foo.bar.configuration.FooStreams;
import com.foo.bar.configuration.BarStreams;
import com.foo.bar.domain.Foo;
import com.foo.bar.domain.Bar;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;
#Service
#Slf4j
public class KafkaPublisherService {
#Autowired
private BarStreams barStreams;
#Autowired
private FooStreams fooStreams;
public void sendBar(final Bar bar) {
log.info("Publishing bar to kafka {}", bar);
MessageChannel messageChannel = barStreams.postBarToOutChanel();
messageChannel.send(MessageBuilder
.withPayload(bar)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
.build());
}
public void sendFoo(final Foo foo) {
log.info("Publishing foo to kafka {}", foo);
MessageChannel messageChannel = fooStreams.postFooToOutChanel();
messageChannel.send(MessageBuilder
.withPayload(foo)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
.build());
}
}
application.properties
spring.cloud.stream.kafka.binder.brokers=localhost:9092
spring.cloud.stream.bindings.foo-out.destination=feedback
spring.cloud.stream.bindings.foo-out.contentType=application/json
spring.cloud.stream.bindings.bar-out.destination=review
spring.cloud.stream.bindings.bar-out.contentType=application/json

Error creating bean with name 'mongoTemplate' while connecting mongodb through Spring

I am trying to connect mongoDb with Spring's mongoTemplate. I also tried changing version of 'spring-data-mongodb' from 1.7.2.RELEASE to 1.8.2.RELEASE, but even that didn't work.
Below is my code as used in the project.
Here's my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.storeApp</groupId>
<artifactId>storeApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Store Application</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<!-- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.4.RELEASE</version>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>storeApp</finalName>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
My SpringMongoConfig file
package com.storeApp.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoFactoryBean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.MongoClient;
#Configuration
public class SpringMongoConfig1 {
public #Bean
MongoDbFactory mongoDbFactory() throws Exception{
return new SimpleMongoDbFactory(new MongoClient(), "storeApp");
}
public #Bean
MongoTemplate mongoTemplate() throws Exception{
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
return mongoTemplate;
}
// ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
// MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
}
This is my main class
package com.storeApp.core;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.storeApp.config.SpringMongoConfig1;
import com.storeApp.config.SpringMongoConfig2;
import com.storeApp.model.Store;
public class StoreMainApp {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig1.class);
MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
Store store = new Store("Sample store 1", "Street 1", "City 1", (float) 35.4);
System.out.println("into main method");
// mongoOperation.save(store);
}
}
Stacktrace :
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:12}] to 127.0.0.1:27017
Oct 18, 2016 10:08:47 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 10]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=1546838}
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in com.storeApp.config.SpringMongoConfig1: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at com.storeApp.core.StoreMainApp.main(StoreMainApp.java:20)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 13 more
Caused by: java.lang.NoSuchMethodError: org.springframework.data.util.ClassTypeInformation.from(Ljava/lang/Class;)Lorg/springframework/data/util/ClassTypeInformation;
at org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper.<clinit>(DefaultMongoTypeMapper.java:49)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.<init>(MappingMongoConverter.java:111)
at org.springframework.data.mongodb.core.MongoTemplate.getDefaultMongoConverter(MongoTemplate.java:2039)
at org.springframework.data.mongodb.core.MongoTemplate.<init>(MongoTemplate.java:217)
at org.springframework.data.mongodb.core.MongoTemplate.<init>(MongoTemplate.java:202)
at com.storeApp.config.SpringMongoConfig1.mongoTemplate(SpringMongoConfig1.java:25)
at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96.CGLIB$mongoTemplate$0(<generated>)
at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96$$FastClassBySpringCGLIB$$52d3ef2d.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
at com.storeApp.config.SpringMongoConfig1$$EnhancerBySpringCGLIB$$81e5bc96.mongoTemplate(<generated>)
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.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 14 more
Not getting where is the problem...
You only need below dependency and it will bring you all needed jars.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
The error java.lang.NoSuchMethodError you are getting is for ClassTypeInformation class. Please check whether spring-data-commons-1.12.3.RELEASE.jar is present after you build your project. If not, then try cleaning up your build environment and update maven project.
A little late to the party, but here is what you need.
If you are trying to use a custom data manipulation rather than using the default inbuilt mongo repositories, then you need a mongoTemplate (kind of jdbc template but lets you define your own implementation of the client, i.e, the mongo client , in this case) and optionally mongoOperations on top of it(Mongo Operations is kind of a wrapper on top of the mongoTemplate)
You need the following dependencies - pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</dependency>
MongoConfig.java
#PropertySource("classpath:application.properties")
public class MongoConfig{
#Value("${spring.data.mongodb.host}")
private String mongoHost;
#Value("${spring.data.mongodb.port}")
private String mongopPort;
#Value("${spring.data.mongodb.database}")
private String mongoDB;
/*Client vs FactoryClient
*
* Factory bean that creates the com.mongodb.MongoClient instance
*
* Classes attributed with #Repostiory may throw mongo related exceptions. Declaring an instance of MonogClientFactoryBean
* helps in translating them to spring data exceptions which can then be caught using #ExceptionHandling
* */
public #Bean MongoClientFactoryBean mongo() throws Exception {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
mongo.setHost("localhost");
MongoClientOptions clientOptions = MongoClientOptions.builder().applicationName("FeddBackAPI_DB")
.connectionsPerHost(2000)
.connectTimeout(4000)
//.maxConnectionIdleTime(1000000000)
.maxWaitTime(3000)
.retryWrites(true)
.socketTimeout(4000)
.sslInvalidHostNameAllowed(true)//this is very risky
.build();
mongo.setMongoClientOptions(clientOptions);
return mongo;
}
}
DataSourceConfig.java
#Configuration
#Import(value=MongoClientFactory.class)
public class DataSourceConfig {
#Autowired
Mongo mongo;
#Autowired
Environment env;
#Bean
public String test() {
System.out.println("mongo"+mongo);
return "rer";
}
#Bean
#Qualifier("customMongoTemplate")
public MongoTemplate mongoTemplate() {
//MongoClient is the actual pool used by mongo. Create it using client factory then, autoclosing of threads are handled on its own
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
MongoTemplate template = new MongoTemplate(factory);
return template;
}
#Bean
#Qualifier(value="customMongoOps")
public MongoOperations mongoOps() {
MongoOperations ops = mongoTemplate();
return ops;
}
#Bean
public MongoDbFactory factory() {
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
return factory;
}
// #Bean
// public GridFsTemplate gridFsTemplate() {
// return new GridFsTemplate(mongo, converter)
// }
}
This should successfully create the mongoTemplate and mongoOperations and you should be able to make use of them in your DAO or service and access them.
PersonService.java
#Service
public class PersonService {
#Autowired
private PersonRepository personRepo;
#Autowired
PersonSequenceServiceImpl seqService;
#Autowired
#Qualifier(value="customMongoOps")
MongoOperations mongoOps;
public List<Person> findAllPersons() {
return personRepo.findAll();
}
public List<Person> createAndFindAllPersons() {
Person p1 = new Person( "another1", "ll1", 30);
Person p2 = new Person( "another2", "ll2", 30);
if(!mongoOps.collectionExists(Person.class)) {
mongoOps.dropCollection("Person_table");
}
//return personRepo.save(person);
System.out.println("P1 data before inserting:"+p1);
mongoOps.insert(Arrays.asList(p1,p2), Person.class);
//mongoOps.dropCollection(Person.class);
return mongoOps.findAll(Person.class);
}
}
I know it's not a technically justified solution. But after trying several alternatives, I just closed Eclipse and deleted all the .m2 folder content.
Then, I retried to import the Project ina new Workspace and compiled.
Surprise! This time it worked :)
Sometimes rebooting works ;)

Categories

Resources