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

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.

Related

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?

Spring Data Error with specific object

I have the following repository:
public interface ICredCardRepository extends JpaRepository<CredCardEntity, Long> {
public List<CredCardEntity> findByUserId(Long userId);
}
The UserId attribute is declared like this in the CredCardEntity:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "UserId", nullable = false)
private UserEntity UserId;
I have the following exception:
Caused by: java.lang.RuntimeException:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'ICredCardRepository': Invocation of init
method failed; nested exception is java.lang.IllegalArgumentException:
Could not create query metamodel for method public abstract
java.util.List
org.wpattern.frameworks.jsf.primefaces.model.repositories.ICredCardRepository.findByUserId(java.lang.Long)!
at
io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:223)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
at
org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
[jboss-msc-1.2.2.Final.jar:1.2.2.Final] at
org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
[jboss-msc-1.2.2.Final.jar:1.2.2.Final]
Based on this exception I have changed the method findByUserId like that:
public List<CredCardEntity> findByUserId(UserEntity userId);
But it does not work. Could you help me out, please?
Simply change UserId property name to user. In this case 'UserId' in your method will be pointed to the id property of the User.
Also I think #JoinColumn is unnecessary here, you can remove it...

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/

Superclass has no null constructors but no arguments were given

Im using Spring Social in my application:
<spring.framework.version>3.2.0.RELEASE</spring.framework.version>
<hibernate.version>4.1.9.Final</hibernate.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<org.springframework.social-version>1.1.0.BUILD-SNAPSHOT</org.springframework.social-version>
<org.springframework.social.facebook-version>1.1.0.BUILD-SNAPSHOT</org.springframework.social.facebook-version>
<org.springframework-version>3.2.1.RELEASE</org.springframework-version>
<org.springframework.security.crypto-version>3.1.3.RELEASE</org.springframework.security.crypto-version>
When I apply
private final Facebook facebook;
#Inject
public SearchController(Facebook facebook) {
this.facebook = facebook;
}
To my HomeController:
#Controller
public class HomeController {
private final Facebook facebook;
#Inject
public HomeController(Facebook facebook) {
this.facebook = facebook;
}
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
return "home";
}
}
The injection works like intented and I can get information from facebook. However, when I apply it to one of my other Cotrollers like this one
#Controller
#Transactional
#RequestMapping(value = "/search")
public class SearchController {
private static final Logger logger = LoggerFactory.getLogger(SearchController.class);
private final Facebook facebook;
#Inject
public SearchController(Facebook facebook) {
this.facebook = facebook;
}
#PersistenceContext
private EntityManager entityManager;
...
I getting this error:
mar 05, 2013 12:46:36 EM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/project] threw exception [Request processing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchController' defined in file [C:\Users\Nilsi\Downloads\springsource\vfabric-tc-server-developer-2.7.2.RELEASE\base-instance\wtpwebapps\course_info\WEB-INF\classes\com\courseinfo\project\controller\SearchController.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.courseinfo.project.controller.SearchController]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given] with root cause
java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at org.springframework.cglib.proxy.Enhancer.emitConstructors(Enhancer.java:721)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:499)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.springframework.cglib.proxy.Enhancer.create(Enhancer.java:285)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:111)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:477)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:412)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1492)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
at org.springframework.web.method.HandlerMethod.createWithResolvedBean(HandlerMethod.java:202)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:233)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:55)
at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:297)
at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1091)
at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1076)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:896)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
My guess is that I can't inject facebook to a Controller with annotation #Transactional?
CGlib has one important restriction: the target class must provide a default constructor.
If you use property-based injection instead of constructor-based injection, the problem will go away.
I just created an empty default constructor to deal with this.
If you are using Lombok in your code, then you can just add the following annotation to get rid of this error:
#NoArgsConstructor
public class SearchController {