Getting ConverterNotFoundException in basic springbatch program - spring-batch

I am trying to create a springboot batch application and am getting below exception
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.util.LinkedHashMap<?, ?>] to type [#org.springframework.lang.Nullable java.util.Map<java.lang.Class<?>, java.lang.Class<java.beans.PropertyEditor>>] for value '{org.springframework.batch.item.file.transform.Range[]=org.springframework.batch.item.file.transform.RangeArrayPropertyEditor}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [#org.springframework.lang.Nullable java.lang.Class<?>]
caused by
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [#org.springframework.lang.Nullable java.lang.Class<?>]
It seems this error comes when spring tries to initialize org.springframework.beans.factory.config.CustomEditorConfigurer
I have not provide this bean definition in my code.
here are the key pieces of the code:
A. Job definition (in XML):
<batch:job id="testBatchJob" job-repository="jobRepository">
<batch:step id="step_test">
<batch:tasklet ref="createModifyTargetTable"/>
</batch:step>
</batch:job>
B. other definitions (in java)
#Configuration
#ImportResource({"classpath:database-config.xml","classpath:batchflows-config.xml"})
public class SpringConfig {
#Bean
public PlatformTransactionManager transactionManager() {
return new ResourcelessTransactionManager();
}
#Bean
public JobLauncher jobLauncher(JobRepository jobRepository) throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
#Bean
public JobRepository jobRepository(#Qualifier("metadata-db") DataSource dataSource,
PlatformTransactionManager transactionManager) throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource);
factory.setDatabaseType("POSTGRES");
factory.setTransactionManager(transactionManager);
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public Tasklet createModifyTargetTable(){
return new CreateModifyTargetTable();
}
}
Complete stacktrace
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.util.LinkedHashMap<?, ?>] to type [#org.springframework.lang.Nullable java.util.Map<java.lang.Class<?>, java.lang.Class<java.beans.PropertyEditor>>] for value '{org.springframework.batch.item.file.transform.Range[]=org.springframework.batch.item.file.transform.RangeArrayPropertyEditor}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [#org.springframework.lang.Nullable java.lang.Class<?>]
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:46) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:191) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:129) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:585) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:604) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:219) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1714) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1670) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1417) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204) [spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:171) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:705) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at com.edci.datacopy.core.app.main.ApplicationLauncher.main(ApplicationLauncher.java:24) ~[classes/:na]
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [#org.springframework.lang.Nullable java.lang.Class<?>]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.core.convert.support.MapToMapConverter.convertKey(MapToMapConverter.java:122) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.core.convert.support.MapToMapConverter.convert(MapToMapConverter.java:84) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:40) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 21 common frames omitted

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.

java.lang.IllegalStateException: Failed to load ApplicationContext error in Spring Boot

I am new to unit testing and I have to test my methods in spring boot.
I created application with Spring Security JWT Authentication + PostgreSQL – RestAPIs SpringBoot + Spring MVC + Spring JPA from this link
then I created controller for users to edit update ect.
My users controller looks like this
#RestController
#RequestMapping("/users")
public class Users {
#Autowired
private UserService userService;
#GetMapping(value = "/*")//can access with this root
#PreAuthorize("hasRole('ADMIN')") //Only admin can view all users' details
public List<User> AllUsers(){
return this.userService.getAllUsers();
}
#GetMapping(value = "/{username}")//can access with this root
public User GetOneUser(#PathVariable(value = "username") String username){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String auth_name = auth.getName(); //get logged in username
if(auth_name.equals(username)||this.userService.isAdmin(auth_name)){//admin and user can see the details
return this.userService.getUser(username);
}
else{
return null;
}
}
#DeleteMapping(value = "/{id}")//can access with this root
#PreAuthorize("hasRole('ADMIN')") //Only admin can delete user
public void DeleteUser(#PathVariable(value = "id") Long id){
this.userService.deleteUser(id);
}
#PostMapping(value = "/{username}")//can access with this root
public User EditUser(#PathVariable(value = "username") String username,#RequestBody SignUpForm user) {//only user can edit
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String auth_name = auth.getName(); //get logged in username
User upUser=null;
if(auth_name.equals(username)){
upUser=this.userService.updateUser(username,user);
}
return upUser;
}
}
then I created UserService like this:
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
PasswordEncoder encoder;
public List<User> getAllUsers(){
// return topics;
List<User> users=new ArrayList<>();
userRepository.findAll().forEach(users::add);
return users;
}
public boolean isAdmin(String username){
boolean flag=false;
if(this.userRepository.existsByUsername(username)){
User user=this.userRepository.findByUsername(username).get();
Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
if(user.getId().equals(adminRole.getId())){
flag=true;
}
}
return flag;
}
public User getUser(String username){
return userRepository.findByUsername(username).orElse(null);
}
public User updateUser(String username, SignUpForm user) {
if(userRepository.existsByUsername(username)) {
User ExistingUser=userRepository.findByUsername(username).get();
if(ExistingUser.getName()!=user.getName()){
ExistingUser.setName(user.getName());
}
if(ExistingUser.getUsername()!=user.getUsername()){
ExistingUser.setUsername(user.getUsername());
}
if(ExistingUser.getPassword()!=user.getPassword()){
ExistingUser.setPassword(encoder.encode(user.getPassword()));
}
if(ExistingUser.getEmail()!=user.getEmail()){
ExistingUser.setEmail(user.getEmail());
}
Set<String> Roles =user.getRole();
Set<Role> roles = new HashSet<>();
Roles.forEach(role -> {
switch(role) {
case "admin":
Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
roles.add(adminRole);
break;
case "pm":
Role pmRole = roleRepository.findByName(RoleName.ROLE_PM)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
roles.add(pmRole);
break;
default:
Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
roles.add(userRole);
}
});
if(ExistingUser.getRoles()!=roles){
ExistingUser.setRoles(roles);
}
userRepository.save(ExistingUser);
}
return userRepository.findByUsername(user.getUsername()).get();
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
it works.
But then I created class for testing that tests getUser() method from UserService
#WebMvcTest
#RunWith(SpringRunner.class)
public class UserServiceTest {
#MockBean
UserRepository repository;
#Autowired
UserService userService;
#Test
public void getUserTest(){
User user=this.userService.getUser("arife");
assertThat(user).isNotNull();
}
}
But it gives me error that looks like this:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:95)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:79)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:54)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authRestAPIs': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:598)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:847)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 25 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:598)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:392)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1255)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1175)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595)
... 43 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1662)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1221)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1175)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595)
... 65 more
Please can someone help me?
Is pretty hard to follow up your problem if you don't add more details (log trace, code snapshots...)
But maybe you can find this pet project done by me (https://github.com/geeksusma/jwt-rest-controller)
Basically is a RestController which works with JWT.
I hope it could help
Now I wrote like this
#DataJpaTest
#RunWith(SpringRunner.class)
public class UserServiceTest {
#MockBean
UserService userService;
#Test
public void getUserTest(){
assertThat(this.userService.getUser("arife")).isNotNull();
}
}
and then I added new File application-test.properties
#ActiveProfiles("test")
#PostgreSQL
spring.datasource.url=jdbc:postgresql:
spring.datasource.username=
spring.datasource.password=
spring.jpa.generate-ddl=true
now it gives me error
java.lang.AssertionError:
Expecting actual not to be null
at springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.model.UserServiceTest.getUserTest(UserServiceTest.java:59)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I think that is not connected to database

javax.ejb.CreateException: Could not create stateless EJB with glassfish and boneCP on intellij-idea

I recently began to use Glassfish and boneCP on intellij idea with a simple web app, but there's a bug I can't understand. I believe I followed all the steps in the tutorial.
My model goes like this
#Entity
public class Song implements Serializable {
#Id
private String id;
private String title;
private LocalDate lastPlayed;
private int playCount;
public Song() {
title = "Chant sans titre";
id = generateId(title);
lastPlayed = LocalDate.ofEpochDay(0);
playCount = 0;
}
The EJB
#Stateless
public class SongDAO {
#PersistenceUnit(unitName = "statisthira_song")
private EntityManager em;
public void create(Song song){
try {
em.persist(song); } catch (Exception e) { e.printStackTrace(); }
}
the Servlet
#WebServlet(urlPatterns = "/new-song")
public class NewSongActionBean extends HttpServlet {
#EJB
SongDAO dao;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Song song = new Song();
song.setTitle("This is not a Test - Toby Mac");
song.setId(song.generateId(song.getTitle()));
dao.create(song);
this.getServletContext().getRequestDispatcher("/WEB-INF/newsong.jsp").forward(request, response);
}
}
My persistence.xml file under META-INF
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="statisthira_song" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/bonecp_resource</jta-data-source>
<class>statis.hira.model.Song</class>
</persistence-unit>
</persistence>
the server runs without any problem, and when I check the jdbc connection pool with a ping, it succeeds. But when I try to access the url "/new-song", I get this error message
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
here's a sample of the stacktrace
javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:435)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2579)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1971)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy194.create(Unknown Source)
at statis.hira.dao.__EJB31_Generated__SongDAO__Intf____Bean__.create(Unknown Source)
at statis.hira.servlets.NewSongActionBean.doGet(NewSongActionBean.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:700)
at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:246)
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:430)
... 37 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:514)
at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:97)
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:698)
... 39 more
Caused by: java.lang.IllegalStateException: Exception attempting to inject Env-Prop: statis.hira.dao.SongDAO/em#Field-Injectable Resource. Class name = statis.hira.dao.SongDAO Field name=em#java.lang.String### into class statis.hira.dao.SongDAO: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:175)
at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46)
at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:73)
at org.jboss.weld.injection.producer.StatelessSessionBeanInjector.inject(StatelessSessionBeanInjector.java:60)
at org.jboss.weld.injection.producer.ejb.SessionBeanInjectionTarget.inject(SessionBeanInjectionTarget.java:140)
at org.glassfish.weld.services.JCDIServiceImpl.injectEJBInstance(JCDIServiceImpl.java:257)
at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1748)
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:475)
... 41 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Env-Prop: statis.hira.dao.SongDAO/em#Field-Injectable Resource. Class name = statis.hira.dao.SongDAO Field name=em#java.lang.String### into class statis.hira.dao.SongDAO: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:740)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:507)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:170)
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:165)
... 48 more
Caused by: java.lang.IllegalArgumentException: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:688)
... 51 more
You should change from
#PersistenceUnit(unitName = "statisthira_song")
to
#PersistenceContext(name= "statisthira_song")
#PersistenceUnit is used to inject EntityManagerFactory and #PersistenceContext is used to inject EntityManager

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.