Getting Could not autowire field: private com.jio.asp.service.MongoDBBussinessDelegate - mongodb

Getting error while autowired MongoDBBussinessDelegate
Getting Null Pointer Exception if I intialize MongoDBBussinessDelegate as a class object.
I tried to autowired Mongotemplate in controller also but getting the same error.
error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDBController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jio.asp.service.MongoDBBussinessDelegate com.jio.asp.controller.MongoDBController.mongoDBBussinessDelegate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDBBussinessDelegate': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.mongodb.core.MongoTemplate com.jio.asp.service.MongoDBBussinessDelegate.mongoTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.mongodb.core.MongoTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4809)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5251)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1816)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jio.asp.service.MongoDBBussinessDelegate com.jio.asp.controller.MongoDBController.mongoDBBussinessDelegate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDBBussinessDelegate': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.mongodb.core.MongoTemplate com.jio.asp.service.MongoDBBussinessDelegate.mongoTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.mongodb.core.MongoTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 26 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDBBussinessDelegate': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.mongodb.core.MongoTemplate com.jio.asp.service.MongoDBBussinessDelegate.mongoTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.mongodb.core.MongoTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 28 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.mongodb.core.MongoTemplate com.jio.asp.service.MongoDBBussinessDelegate.mongoTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.mongodb.core.MongoTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 39 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.mongodb.core.MongoTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 41 more
Controller
package com.jio.asp.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.jio.asp.domain.Message;
import com.jio.asp.model.Person;
import com.jio.asp.service.MongoDBBussinessDelegate;
#RestController
public class MongoDBController {
#Autowired
private MongoDBBussinessDelegate mongoDBBussinessDelegate;
#RequestMapping("/")
#ResponseBody
public String welcome(#RequestBody Map<String, String> user) {//Welcome page, non-rest
// MongoDBBussinessDelegate mongoDBBussinessDelegate = new MongoDBBussinessDelegate();
//Person person = new Person();
//person.setId("2");
//person.setName("Raj");
//m.addPerson(person);
List<Person> lperson = mongoDBBussinessDelegate.listPerson();
//m.addPerson(user);
//System.out.println(mongoTemplate.getCollectionNames());
return "done";
}
#RequestMapping("/hello/{player}")
public Message message(#PathVariable String player) {//REST Endpoint.
Message msg = new Message(player, "Hello " + player);
return msg;
}
}
Service
package com.jio.asp.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import com.jio.asp.model.Person;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
#Service
public class MongoDBBussinessDelegate {
#Autowired
private MongoTemplate mongoTemplate;
public static final String COLLECTION_NAME = "users";
public void addPerson(Map<String, String> user) {
/* if (!mongoTemplate.collectionExists(Person.class)) {
mongoTemplate.createCollection(Person.class);
}*/
//System.out.println(mongoTemplate.);
DBCollection col = mongoTemplate.getCollection(COLLECTION_NAME);
/*Map<String,String> map = new HashMap<>();
map.put("username", "nishant");
map.put("pass", "pass ho gya");*/
BasicDBObject obj = new BasicDBObject(user);
col.insert(obj);
//person.set_id(UUID.randomUUID().toString());
//mongoTemplate.insert(person, COLLECTION_NAME);
//mongoTemplate.save(person,"person");
}
public List<Person> listPerson() {
return mongoTemplate.findAll(Person.class,COLLECTION_NAME);
}
public void deletePerson(Person person) {
mongoTemplate.remove(person, COLLECTION_NAME);
}
public void updatePerson(Person person) {
mongoTemplate.insert(person, COLLECTION_NAME);
}
public static void main(String [] args){
MongoClient m = new MongoClient("localhost");
System.out.println(m.getDatabaseNames());
MongoTemplate t = new MongoTemplate(m, "aadhaar");
System.out.println(t.getCollectionNames());
/*DBCollection col = t.getCollection("users");
Map<String,String> map = new HashMap<>();
map.put("username", "nishant");
map.put("pass", "pass ho gya");
BasicDBObject obj = new BasicDBObject(map);
col.insert(obj);*/
// System.out.println(t.findAll(Person.class, COLLECTION_NAME));
}
}
Dispatcher servlet
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<context:component-scan base-package="com.jio.asp.controller" />
<context:component-scan base-package="com.jio.asp.domain" />
<context:component-scan base-package="com.jio.asp.model" />
<context:component-scan base-package="com.jio.asp.service" />
<bean id="mongo" class="com.mongodb.MongoClient">
<constructor-arg name="host" value="127.0.0.1" />
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="aadhaar" />
</bean>
</beans>

Related

Integration test using testcontainers((MongoDB issues)) are failing after upgrading to SpringBoot 2.6.6

I have updated SpringBoot version from 2.1.6 to 2.6.6 and after starting integration tests with testcontainers I am receiving below errors:
First error is:
13:25:08.793 [main] ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'approvalResource': Unsatisfied dependency expressed through field 'queryApprovals'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'queryApprovals': Unsatisfied dependency expressed through field 'approvalRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'approvalRepository' defined in adapters.outbound.repositories.ApprovalRepository defined in #EnableMongoRepositories declared on Licenses: Cannot create inner bean '(inner bean)#66589252' of type [org.springframework.data.repository.core.support.RepositoryFragmentsFactoryBean] while setting bean property 'repositoryFragments'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#66589252': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'squealRepositoryImplFragment': Cannot resolve reference to bean 'squealRepositoryImpl' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'squealRepositoryImpl': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Unsatisfied dependency expressed through method 'mongoDatabaseFactory' parameter 0; nested exception is 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.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
then:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Unsatisfied dependency expressed through method 'mongoDatabaseFactory' parameter 0; nested exception is 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.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
... 169 common frames omitted
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.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
... 183 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
... 197 common frames omitted
Caused by: java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
at org.springframework.util.Assert.state(Assert.java:76)
at org.springframework.boot.autoconfigure.mongo.MongoPropertiesClientSettingsBuilderCustomizer.validateConfiguration(MongoPropertiesClientSettingsBuilderCustomizer.java:61)
at org.springframework.boot.autoconfigure.mongo.MongoPropertiesClientSettingsBuilderCustomizer.customize(MongoPropertiesClientSettingsBuilderCustomizer.java:52)
at org.springframework.boot.autoconfigure.mongo.MongoClientFactorySupport.customize(MongoClientFactorySupport.java:55)
at org.springframework.boot.autoconfigure.mongo.MongoClientFactorySupport.createMongoClient(MongoClientFactorySupport.java:49)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration.mongo(MongoAutoConfiguration.java:55)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 198 common frames omitted
Initializer class:
#Slf4j
public class IntegrationTestContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> {
private static final MongoDBContainer mongoDbContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.18-xenial")).withReuse(true);
private static final KeycloakContainer keycloakContainer = new KeycloakContainer("jboss/keycloak:12.0.4")
.withRealmImportFile("test-realm.json")
.withAdminUsername("admin")
.withAdminPassword("password")
.withReuse(true)
.withStartupTimeout(Duration.ofMinutes(5));
private static final GenericContainer<?> mailContainer = new GenericContainer<>(DockerImageName.parse("reachfive/fake-smtp-server:0.8.1")).withReuse(true).withExposedPorts(1025);
static {
mailContainer.start();
mongoDbContainer.start();
keycloakContainer.start();
}
#Override
public void initialize(#NotNull ConfigurableApplicationContext configurableApplicationContext) {
log.info("MongoDB URI: {}", mongoDbContainer.getReplicaSetUrl());
log.info("Keycloak URI: {}", keycloakContainer.getAuthServerUrl());
log.info("Mail server Port: {}", mailContainer.getMappedPort(1025));
TestPropertyValues values = TestPropertyValues.of(
"spring.data.mongodb.uri=" + mongoDbContainer.getReplicaSetUrl(),
"de.easy.myeasy.licenses.keycloak.username=" + keycloakContainer.getAdminUsername(),
"de.easy.myeasy.licenses.keycloak.password=" + keycloakContainer.getAdminPassword(),
"keycloak.auth-server-url=" + keycloakContainer.getAuthServerUrl(),
"spring.mail.host=" + mailContainer.getHost(),
"spring.mail.port=" + mailContainer.getMappedPort(1025),
"spring.mail.properties.mail.smtp.auth=false",
"spring.mail.properties.mail.smtp.starttls.enable=false"
);
values.applyTo(configurableApplicationContext);
}
}
BaseIT class:
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
#ActiveProfiles("test")
#Slf4j
#ContextConfiguration(initializers = IntegrationTestContextInitializer.class)
public class BaseIntegrationTest {
#Autowired
protected ObjectMapper objectMapper;
#Autowired
protected MockMvc mockMvc;
#Autowired
protected MongoTemplate mongoTemplate;
#Autowired
protected WebApplicationContext webApplicationContext;
#SuppressWarnings("unused")
#Autowired
private KeycloakService keycloakService;
#Autowired
private KeycloakUserAdminService keycloakUserAdminService;
#Autowired
private UserRepository userRepository;
#Autowired
private QueryProducts queryProducts;
private final String[] downloadWhitelist = {"bit.ly", "downloads.com", "updatedlink.com", "newsownloadlink.com"};
#BeforeEach
public void setup() throws UserServiceException {
log.info("--------- Integration Test Starting ---------");
ReflectionTestUtils.setField(queryProducts, "downloadWhitelist", downloadWhitelist);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
seedIntegrationTestUsers();
}
private void removeUser(String name){
try{
keycloakUserAdminService.deleteUser(name);
} catch (UserServiceException e) {
log.debug("Delete {} failed", name,e);
}
}
#AfterEach
public void tearDown() {
Stream<String> collectionNames = mongoTemplate.getCollectionNames().stream().filter(cName -> !cName.startsWith("system"));
collectionNames.forEach(cName -> mongoTemplate.findAllAndRemove(new Query(), cName));
removeUser("it_tester#tester.com");
removeUser("it_tester2#tester.com");
removeUser("it_tester3#customera.com");
log.info("--------- Integration Test Stopped ---------");
}
public void seedIntegrationTestUsers() throws UserServiceException {
userRepository.save(User.builder().username("it_tester#tester.com").email("it_tester#tester.com").build());
userRepository.save(User.builder().username("it_tester2#tester.com").email("it_tester2#tester.com").build());
KeycloakUser keycloakUser = new KeycloakUser();
keycloakUser.setUsername("it_tester#tester.com");
keycloakUser.setEmail("it_tester#tester.com");
keycloakUser.setFirstName("tester");
keycloakUser.setLastName("tester");
keycloakUser.setEnabled(true);
KeycloakUser keycloakUser2 = new KeycloakUser();
keycloakUser2.setUsername("it_tester2#tester.com");
keycloakUser2.setEmail("it_tester2#tester.com");
keycloakUser2.setFirstName("tester2");
keycloakUser2.setLastName("tester2");
keycloakUser2.setEnabled(true);
KeycloakUser keycloakUser3 = new KeycloakUser();
keycloakUser3.setUsername("it_tester3#customera.com");
keycloakUser3.setEmail("it_tester3#customera.com");
keycloakUser3.setFirstName("tester3");
keycloakUser3.setLastName("tester3");
keycloakUser3.setEnabled(true);
keycloakUserAdminService.createUser(keycloakUser);
keycloakUserAdminService.createUser(keycloakUser2);
keycloakUserAdminService.createUser(keycloakUser3);
}
}
Test class for loading context:
public class ContextLoadIntegrationTest extends BaseIntegrationTest{
#Test
void contextLoads() {
System.out.println("Context loads!");
}
}
Moreover I have #EnableMongoRepositories annotation in Application:
#SpringBootApplication
#EnableMongoRepositories(basePackages = {"adapters.outbound.repositories", "ps.squeal"})
public class MyApplication {
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException {
SpringApplication.run(MyApplication.class, args);
}
}
It is working with Spring boot 2.1.6 but after migrating to 2.6.6 it is throwing errors. What is missing here to make it work? I am using JUnit5.
I have commented spring.data.mongodb.* in all properties files and it worked.
Looks like Spring was not using test profile as stated in #ActiveProfiles("test") annotation.

Unit Testing Spring Services with actual Repository with in memory database

I am trying to test my #Service with the actual object of Spring Data Repository, where I am trying to use in memory database.I am using below annotation in my unit test.
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#EnableJpaRepositories
#SpringBootTest(classes = {MyService.class})
public class T24PortfolioRequestHandlerTest {
#Autowired
private MyService myService;
#Autowired
private MyRepository myRepository;
#Test
public void handleRequest() {
String output = myService.handleRequest(testData, "123", "TEST");
Assert.assertNotNull(output);
Assert.assertEquals("TESTING", output);
}
}
I am getting below exception while running the test.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.....respository.MyRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
If I specify MyRepository.class in SpringBootConfiguratio(classes={MyService.class, MyRepository.class}) I am getting below error.
org.springframework.beans.BeanInstantiationException: Failed to instantiate [...respository.MyRepository]: Specified class is an interface
Is there any another way to tell spring boot about my repositories?

java.lang.ClassNotFoundException: org.springframework.data.util.CloseableIterator

While deploying Spring based web application, I am getting this exception and not able to find any jar which has the class CloseableIterator. Kindly suggest/guide!
Here is the stack trace of the server while deploying the app
HTTP Status 500 - Servlet.init() for servlet rest threw exception
type Exception report
message Servlet.init() for servlet rest threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet rest threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1721)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersRepository': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.mongodb.core.MongoTemplate com.miet.kmpro.dao.UsersRepository.mongoTemplate; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/util/CloseableIterator
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
.................
root cause
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.mongodb.core.MongoTemplate com.miet.kmpro.dao.UsersRepository.mongoTemplate; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/util/CloseableIterator
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1721)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
root cause
java.lang.NoClassDefFoundError: org/springframework/data/util/CloseableIterator
java.lang.Class.getDeclaredMethods0(Native Method)
java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
java.lang.Class.getDeclaredMethods(Class.java:1975)
org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:609)
org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:521)
org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:507)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:241)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1069)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1042)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1192)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1721)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
root cause
java.lang.ClassNotFoundException: org.springframework.data.util.CloseableIterator
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
java.lang.Class.getDeclaredMethods0(Native Method)
java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
java.lang.Class.getDeclaredMethods(Class.java:1975)
org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:609)
org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:521)
org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:507)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:241)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1069)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1042)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1192)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1721)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.53 logs.
Apache Tomcat/7.0.53
Libraries I am using in my project
com.springsource.org.aopalliance-1.0.0.jar
commons-logging-1.1.1.jar
jackson-annotations-2.4.1.jar
jackson-core-2.4.1.jar
jackson-databind-2.4.1.jar
jdom-1.1.3.jar
jstl-1.2.jar
mongo-java-driver-2.9.0.jar
org.springframework.data.core_1.3.1.release.jar
org.springframework.transaction_3.0.5.RELEASE.jar
rome-1.0.jar
spring-aop-4.2.4.RELEASE.jar
spring-aspects-4.2.4.RELEASE.jar
spring-beans-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-context-support-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-data-commons-1.8.0.RELEASE.jar
spring-data-commons-core-1.4.0.RELEASE.jar
spring-data-mongodb-1.8.2.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
spring-instrument-4.2.4.RELEASE.jar
spring-instrument-tomcat-4.2.4.RELEASE.jar
spring-jdbc-4.2.4.RELEASE.jar
spring-jms-4.2.4.RELEASE.jar
spring-messaging-4.2.4.RELEASE.jar
spring-orm-4.2.4.RELEASE.jar
spring-tx-4.2.4.RELEASE.jar
spring-web-4.2.4.RELEASE.jar
spring-webmvc-4.2.4.RELEASE.jar
rest-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.miet.kmpro.beans"/>
<context:component-scan base-package="com.miet.kmpro.dao"/>
<context:component-scan base-package="com.miet.kmpro.springctrls"/>
<mvc:annotation-driven />
<!-- Define the MongoTemplate which handles connectivity with MongoDB -->
<beans:bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<beans:constructor-arg name="mongo" ref="mongo" />
<beans:constructor-arg name="databaseName" value="kmpro" />
</beans:bean>
<!-- Factory bean that creates the MongoDB instance -->
<beans:bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<beans:property name="host" value="localhost"/>
</beans:bean>
<!-- Use this post processor to translate any MongoExceptions thrown in #Repository annotated classes -->
<beans:bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<!-- JSON Support -->
<!--<bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>-->
<!--<bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>-->
</beans:beans>
UserDetails.java
package com.miet.kmpro.beans;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
//import org.springframework.web.bind.annotation.Id;
#Document
public class UserDetails{
#Id
private String userID;
private String userName;
private String mailID;
private int roleID;
private Subscriptions subscriptions;
private String firstName;
private String lastName;
public UserDetails(String userID, String userName, String mailID, int roleID, Subscriptions subscriptions, String firstName, String lastName){
super();
this.userID=userID;
this.userName=userName;
this.mailID=mailID;
this.roleID=roleID;
this.subscriptions=subscriptions;
this.firstName=firstName;
this.lastName=lastName;
}
public String getUserID() {return userID;}
public String getUserName(){return userName;}
public String getMailID(){return mailID;}
public int getUserRole() {return roleID;}
public Subscriptions getSubscriptions(){return subscriptions;}
public String getFirstName(){return firstName;}
public String getLastName(){return lastName;}
public void setUserID(String userID) {this.userID=userID;}
public void setUserName(String userName){this.userName=userName;}
public void setMailId(String mailID){this.mailID=mailID;}
public void setUserRole(int roleID) {this.roleID=roleID;}
public void setSubscriptions(Subscriptions subscriptions){this.subscriptions=subscriptions;}
public void setFirstName(String firstName){this.firstName=firstName;}
public void setLastName(String lastName){this.lastName=lastName;}
}
MultiUserResponse.java
package com.miet.kmpro.dao;
import java.util.List;
import com.miet.kmpro.beans.UserDetails;
public class MultipleUserResponse {
private boolean success;
private List<UserDetails> users;
public MultipleUserResponse(boolean success, List<UserDetails> users) {
this.success = success;
this.users = users;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public List<UserDetails> getUsers() {
return users;
}
public void setUsers(List<UserDetails> users) {
this.users = users;
}
}
UserRepository.java
package com.miet.kmpro.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
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 org.springframework.stereotype.Repository;
import com.miet.kmpro.beans.UserDetails;
#Repository
public class UsersRepository{
public static final String COLLECTION_NAME = "users";
#Autowired
private MongoTemplate mongoTemplate;
public void addUser(UserDetails userDetails) {
if (!mongoTemplate.collectionExists(UserDetails.class)) {
mongoTemplate.createCollection(UserDetails.class);
}
mongoTemplate.insert(userDetails, COLLECTION_NAME);
}
public UserDetails getUserByUserName(String userName) {
return mongoTemplate.findOne(
Query.query(Criteria.where("userName").is(userName)), UserDetails.class, COLLECTION_NAME);
}
public List<UserDetails> getAllUsers() {
return mongoTemplate.findAll(UserDetails.class, COLLECTION_NAME);
}
public UserDetails deleteUsers(String userName) {
UserDetails userDetails = mongoTemplate.findOne(
Query.query(Criteria.where("userName").is(userName)), UserDetails.class, COLLECTION_NAME);
mongoTemplate.remove(userDetails, COLLECTION_NAME);
return userDetails;
}
public UserDetails updateIssuer(String userName, UserDetails userDetails) {
Query query = new Query();
query.addCriteria(Criteria.where("userName").is(userName));
Update update = new Update();
update.set("firstName", userDetails.getFirstName());
update.set("lastName", userDetails.getLastName());
mongoTemplate.updateFirst(query, update, UserDetails.class);
return userDetails;
}
}
UsersCntrl.java
package com.miet.kmpro.springrestcntrls;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import com.miet.kmpro.beans.UserDetails;
import com.miet.kmpro.beans.Subscriptions;
import com.miet.kmpro.beans.FeedCategory;
import com.miet.kmpro.dao.UsersRepository;
import com.miet.kmpro.dao.MultipleUserResponse;
import java.util.List;
import java.util.ArrayList;
#RestController
public class UsersCntrl {
#Autowired
private UsersRepository usersRepository;
#CrossOrigin(origins = "http://localhost:8787")
#RequestMapping(value = "/users/{name}", method = RequestMethod.GET, headers="Accept=application/json")
//public String getUserDetails(#PathVariable String name) {
#ResponseBody
public MultipleUserResponse getUserDetails(#PathVariable String name) {
List<UserDetails> allUsers = usersRepository.getAllUsers();
MultipleUserResponse multiUsersInfo = new MultipleUserResponse(true, allUsers);
return multiUsersInfo;
//return "{\"userName\":\"Rishi\"}";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringServiceSample</display-name>
<welcome-file-list>
.......
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
.....
CloseableIterator belongs to the Spring Data Core jar file.
http://mvnrepository.com/artifact/org.springframework.data/spring-data-commons-core
Add this jar to your project if it cannot be found.
Edit:
Sorry posted the wrong link.
Have you tried the following jar file
http://mvnrepository.com/artifact/org.springframework.data/spring-data-commons
The main resolution was given by #blairmeister
You need to clean up your classpath. Remove spring-data-commons-core, org.springframework.data.core, and upgrade the version of spring-data-commons to 1.11.1.RELEASE. You maybe want to get rid of org.springframework.transaction_3.0.5.RELEASE as all other Spring Framework artifacts refer to version 4.2.4.RELEASE
Remaining problems were not related to CloseableIterator class and the main point to understand over here is that whenever we are using the external jars we need to refer the latest stable release of the jars which has the required class files for which the NoClassDefinitionFoundException is thrown. Thanks a lot Stackoverflow for this nice forum!!

Spring #Autowired Failed

When I try to inject my service class using #Autowired, I faced some problem
My Rest Controller:
#RestController
#RequestMapping(value = "/SettlementType")
public class SettlementTypeController extends Abstract4EyeController<SettlementTypeAudit, SettlementType, Integer>{
#Autowired
#Qualifier("settlementTypeService")
SettlementTypeService service;
#Override
public Abstract4EyeService<SettlementTypeAudit, SettlementType, Integer> get4EyeService() {
return service;
}
}
My service:
#Service("settlementTypeService")
public class SettlementTypeService extends Abstract4EyeService<SettlementTypeAudit, SettlementType, Integer> implements IMasterFileUpload<SettlementTypeAudit, SettlementType, Integer>
{
#Autowired
SettlementTypeAuditRepository auditRepository;
//my implementations
}
Interface:
public interface IMasterFileUpload <AuditModel extends Base4Eye, MainModel extends ReadOnlyEntity, ID extends Serializable> {
public List<MainModel> getMainFromCollection(List<Map<String, String>> collection);
}
Abstract4EyeService:
public abstract class Abstract4EyeService<AuditModel extends Base4Eye, MainModel extends ReadOnlyEntity, ID extends Serializable> {
#JsonIgnore
public abstract MainModel getMainEntity(AuditModel auditModel);
}
My Stack Trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settlementTypeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: project.test.rms.service.SettlementTypeService project.test.rms.controller.SettlementTypeController.service; nested exception is java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
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.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at project.test.genie.config.BootConfig.main(BootConfig.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: project.test.rms.service.SettlementTypeService project.test.rms.controller.SettlementTypeController.service; nested exception is java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 16 common frames omitted
Caused by: java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)
at java.lang.reflect.Field.set(Unknown Source)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:557)
... 18 common frames omitted
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settlementTypeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: project.test.rms.service.SettlementTypeService project.test.rms.controller.SettlementTypeController.service; nested exception is java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
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.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at project.test.genie.config.BootConfig.main(BootConfig.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: project.test.rms.service.SettlementTypeService project.test.rms.controller.SettlementTypeController.service; nested exception is java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 16 more
Caused by: java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)
at java.lang.reflect.Field.set(Unknown Source)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:557)
... 18 more
I tried to Inject Settlementype Service, but it throws java.lang.IllegalArgumentException: Can not set project.test.rms.service.SettlementTypeService field project.test.rms.controller.SettlementTypeController.service to com.sun.proxy.$Proxy102 exception
The reason you are having problem autowiring SettlementTypeService is because Spring creates a proxy of that class internally. To work around this, you can create an interface to be implemented by SettlementTypeService and autowire with that interface in your controller.

spring batch jobexplorer issue

We are trying to run a spring batch which is failing with below issue.
My configs :
1) Spring boot
#ComponentScan(basePackages = { "some pkgs” })
#ImportResource("classpath:dataSource.xml")
#EnableAutoConfiguration(exclude = DataSourceTransactionManager.class)
public class CollateralReportGeneratorBootstrapper {
public static void main(String[] args) {
System.exit(SpringApplication.exit(SpringApplication.run(CollateralReportGeneratorBootstrapper.class, args)));
}
}
2) Batch
#Configuration
#EnableBatchProcessing
#ComponentScan(basePackages = { "some pkgs”})
public class ReportGenerator {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
3) Dependencies : spring-batch-core, spring-batch-infrastructure, spring-boot-starter-batch
Please let me know if someone faced this issue or any idea about possible solutions !!
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jobLauncherCommandLineRunner' defined in class path resource [org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 1 of type [org.springframework.batch.core.explore.JobExplorer]: : No qualifying bean of type [org.springframework.batch.core.explore.JobExplorer] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.batch.core.explore.JobExplorer] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:747)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:462)
I would suggest start with following sample and add your launcher class to it...
http://spring.io/guides/gs/batch-processing/