How to resolve FatalBeanException in Spring? - spring

I get the following exception:
org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'modifyPopulatorList$child#0' defined in class path resource [config/cmsfacades-cmsitems-spring.xml]: Initialization of bean failed;
Error creating bean with name 'ordermanagementOrderConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderPopulator' while setting bean property 'populators' with key [0];
Error creating bean with name 'ordermanagementOrderPopulator' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderEntryConverter' while setting bean property 'orderEntryConverter';
Error creating bean with name 'ordermanagementOrderEntryConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderEntryPopulator' while setting bean property 'populators' with key [0];
Error creating bean with name 'warehousingOrderEntryPopulator' defined in class path resource [warehousingfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementProductConverter' while setting bean property 'productConverter';
Error creating bean with name 'ordermanagementProductConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementProductPopulator' while setting bean property 'populators' with key [0];
Error creating bean with name 'ordermanagementProductPopulator' defined in class path resource [ordermanagementfacades-spring.xml]: Error setting property values;
Invalid property 'designerConverter' of bean class [de.hybris.platform.ordermanagementfacades.product.converters.populator.OrdermanagementProductBasicPopulator]: Bean property 'designerConverter' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
This is my bean registration :
<alias name="defaultCustomProductBasicPopulator" alias="productBasicPopulator"/>
<bean id="defaultCustomProductBasicPopulator" parent="defaultProductBasicPopulator"
class="de.hybris.NagAcc.facades.product.converters.populator.CustomProductBasicPopulator">
<property name="designerConverter" ref="designerConverter" />
</bean>
This is the class :
public class CustomProductBasicPopulator<SOURCE extends ProductModel, TARGET extends ProductData> extends ProductBasicPopulator<SOURCE,TARGET> {
private Converter<DesignerModel,DesignerData> designerConverter;
public Converter<DesignerModel, DesignerData> getDesignerConverter() {
return designerConverter;
}
public void setDesignerConverter(Converter<DesignerModel, DesignerData> designerConverter) {
this.designerConverter = designerConverter;
}
#Override
public void populate(SOURCE productModel, TARGET productData) throws ConversionException {
super.populate(productModel, productData);
if (productModel.getDesigner() != null)
{
DesignerData designerData = getDesignerConverter().convert(productModel.getDesigner());
productData.setDesigner(designerData);
}
}
This is the parent bean definition :
<alias name="defaultProductBasicPopulator" alias="productBasicPopulator"/>
<bean id="defaultProductBasicPopulator" parent="baseProductPopulator"
class="de.hybris.platform.commercefacades.product.converters.populator.ProductBasicPopulator">
<property name="productConfigurableChecker" ref="productConfigurableChecker"/>
</bean>
The complete stack trace:
org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'modifyPopulatorList$child#0' defined in class path resource [config/cmsfacades-cmsitems-spring.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementOrderConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderPopulator' while setting bean property 'populators' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementOrderPopulator' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderEntryConverter' while setting bean property 'orderEntryConverter'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementOrderEntryConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderEntryPopulator' while setting bean property 'populators' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'warehousingOrderEntryPopulator' defined in class path resource [warehousingfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementProductConverter' while setting bean property 'productConverter'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementProductConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementProductPopulator' while setting bean property 'populators' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementProductPopulator' defined in class path resource [ordermanagementfacades-spring.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'designerConverter' of bean class [de.hybris.platform.ordermanagementfacades.product.converters.populator.OrdermanagementProductBasicPopulator]: Bean property 'designerConverter' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at de.hybris.platform.core.HybrisContextFactory.build(HybrisContextFactory.java:307)
at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.buildSelf(HybrisContextFactory.java:179)
at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:165)
at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:122)
at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:101)
at de.hybris.platform.core.HybrisContextHolder.getAppCtxFactory(HybrisContextHolder.java:152)
at de.hybris.platform.core.HybrisContextHolder.getApplicationInstance(HybrisContextHolder.java:78)
at de.hybris.platform.core.AbstractTenant.createCoreApplicationContext(AbstractTenant.java:758)
at de.hybris.platform.core.AbstractTenant.doStartupSafe(AbstractTenant.java:799)
... 22 more
According to me all getters and setters are fine, I can not resolve this error. Please help.

I don't have access to hybris sources to have a look (thank god!), but I think it's worth to have a look at the Javadoc of OrdermanagementProductBasicPopulator:
public void populate​(ProductModel productModel, ProductData productData)
Description copied from interface: Populator
Populate the target instance with values from the source instance.
Overrides:
populate in class ProductBasicPopulator
So I guess, the class OrdermanagementProductBasicPopulator extends ProductBasicPopulator but the bean definition of OrdermanagementProductBasicPopulator has your productBasicPopulator as a parent, which means that spring tries to inject the property of your bean definition, which is not a property in the inheritance chain of OrdermanagementProductBasicPopulator.
As mentioned, this is just a guess because I don't see the sources...
If my guess is correct, it depends on your requirements how to get rid of this problem. You can either give your bean a new alias and modify the populator list(s) where necessary or you override the bean alias of OrdermanagementProductBasicPopulator accordingly.
If thats's not the problem, please post the bean definition of OrdermanagementProductBasicPopulator.

Related

How to fix MongoTemplate --> MappingMongoConverter --> BeforeConvertCallback --> MongoTemplate circular dependency?

I am trying to create a custom Auditing callback in order to set the corresponding fields of my MongoDB documents.
This is my callback:
#Order(101)
#Component
#RequiredArgsConstructor
public class AuditingCallback implements BeforeConvertCallback<AuditingDocument<String>> {
private final AuditingConfiguration auditingConfiguration;
#Setter
#Autowired
private MongoTemplate mongoTemplate;
/**
* Entity callback method invoked before a domain object is converted to be persisted. Can return either the same or a
* modified instance of the domain object.
*
* #param entity the domain object to save.
* #param collection name of the collection.
* #return the domain object to be persisted.
*/
#Override
public AuditingDocument<String> onBeforeConvert(AuditingDocument<String> entity, String collection) {
System.out.println("Auditing Callback");
System.out.println(entity);
if(this.isNew(entity)){
System.out.println("Is new");
entity.setCreator(this.auditingConfiguration.getCurrentAuditor().orElse(null));
entity.setCreated(Instant.now());
}else{
System.out.println("Is not new");
// TODO
// Retrieve existing creator, created
Class<AuditingDocument<String>> clazz = (Class<AuditingDocument<String>>) entity.getClass();
AuditingDocument<String> existingEntity = this.mongoTemplate.<AuditingDocument<String>>findById(entity.getId(), clazz);
System.out.println("Existing Entity:");
System.out.println(existingEntity);
entity.setModifier(this.auditingConfiguration.getCurrentAuditor().orElse(null));
entity.setModified(Instant.now());
}
return entity;
}
private boolean isNew(AuditingDocument<String> entity){
return StringUtils.isBlank(entity.getId());
}
}
Now I need to find the existing entity from the DB, to keep the existing creator and created fields, hence the MongoTemplate field.
This results in a circular dependency:
┌─────┐
| mongoTemplate defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]
↑ ↓
| mappingMongoConverter defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]
↑ ↓
| auditingCallback (field private org.springframework.data.mongodb.core.MongoOperations org.myproject.configuration.database.auditing.callbacks.AuditingCallback.mongoOperations)
└─────┘
How can I break this circular dependency?
I also tried with MongoOperations but it is the same.
Note that I am already using the
allow-circular-references: true
property.
Is it not possible to load existing entities during MongoDB events callbacks?
Log 2
Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; 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 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingMongoConverter' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditingCallback': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: 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 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingMongoConverter' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditingCallback': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingMongoConverter' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditingCallback': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditingCallback': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?

Spring Data: Mongo Repository can not be initialized

I'm getting this strange error message when I start my spring boot service:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property storeMpi found for type Patient!
Service can't be started since this exception is raised.
My code is very straight:
public interface PatientRepository
extends MongoRepository<Patient, String>,
QuerydslPredicateExecutor<Patient>,
MPIPatientRepository
{
}
public interface MPIPatientRepository {
Patient storeMpi(Patient patient);
}
You can see, that storeMpi is a method, not an expected field of my Patient entity.
Implementation is straight as well:
#Repository
#RequiredArgsConstructor
public class MPIPatientRepository implements cat.gencat.catsalut.hes.mpi.repository.MPIPatientRepository {
private final MongoTemplate mongoTemplate;
/**
* {#inheritDoc}
*/
#Override
public Patient storeMpi(Patient patient) {
return this.mongoTemplate.save(patient);
}
I don't quite figure out what's wrong.
Formatted root CausedBy is:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ca.uhn.fhir.spring.boot.autoconfigure.FhirAutoConfiguration$FhirRestfulServerConfiguration': Bean instantiation via constructor failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [ca.uhn.fhir.spring.boot.autoconfigure.FhirAutoConfiguration$FhirRestfulServerConfiguration$$EnhancerBySpringCGLIB$$5fe4b535]: Constructor threw exception;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'patientResourceProvider' defined in file [/home/jeusdi/projects/salut/mpi/hes-mpi-fhir-mongodb/target/classes/cat/gencat/catsalut/hes/mpi/providers/PatientResourceProvider.class]: Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'patientService' defined in file [/home/jeusdi/projects/salut/mpi/hes-mpi-fhir-mongodb/target/classes/cat/gencat/catsalut/hes/mpi/service/PatientService.class]: Unsatisfied dependency expressed through constructor parameter 2;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'patientRepository' defined in cat.gencat.catsalut.hes.mpi.repository.PatientRepository defined in #EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed;
nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract cat.gencat.catsalut.hes.mpi.model.Patient cat.gencat.catsalut.hes.mpi.repository.MPIPatientRepository.storeMpi(cat.gencat.catsalut.hes.mpi.model.Patient)! Reason: No property storeMpi found for type Patient!;
nested exception is org.springframework.data.mapping.PropertyReferenceException: No property storeMpi found for type Patient!
Any ideas?

Why creating been in Spring occurs with error?

Hello I am creating program which will communicate and send information using channel. When I run program it doesn't work.
Errors:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-05-02 13:47:37.938 ERROR 12584 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloWorldQueueProducer' defined in file [C:\workspace\target\classes\edu\producer\HelloWorldQueueProducer.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jmsTemplate' defined in class path resource [org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration$JmsTemplateConfiguration.class]: Unsatisfied dependency expressed through method 'jmsTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jmsConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration$SimpleConnectionFactoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jms.connection.CachingConnectionFactory]: Factory method 'cachingJmsConnectionFactory' threw exception; nested exception is java.lang.IllegalStateException: Unable to create ActiveMQConnectionFactory
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.5.jar:5.3.5]
#Component
#RequiredArgsConstructor
public class HelloWorldQueueProducer {
private final JmsTemplate jmsTemplate;
#Scheduled(fixedRate = 2000)
public void sendHello() {
HelloMessage message = HelloMessage.builder()
.id(HelloMessage.nextId())
.createdAt(LocalDateTime.now())
.message("Hello world!")
.build();
jmsTemplate.convertAndSend(JmsConfig.QUEUE_HELLO_WORLD, message);
System.out.println("HelloWorldQueueProducer.sendHello - sent message: " + message);
}
}
Not quite sure about it, but have you defined the necessary properties in your application.properties? You need to set them like this i. e.
spring.artemis.mode=native
spring.artemis.host=localhost
spring.artemis.port=61616
spring.artemis.user=developer
spring.artemis.password=developer
jms.queue.destination=myqueue
Otherwise the autoconfiguration of spring boot wouldn't bootstrap the necessary beans. I had this problem once.

Spring BeanPostProcessor BeanCreationException runtime error

I'm unable to launch hello world app with Spring 4.3.6 Please, help, I don't even know what may be wrong.
Without bean messageService and aop section everything works. But I got this error with config as it is
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'printer' defined in class path resource [config.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#c273d3' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#c273d3': Cannot create inner bean '(inner bean)#1423665' of type [org.springframework.aop.config.MethodLocatingFactoryBean] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1423665': Initialization of bean failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [MessagePrinterService] for bean with name 'messageService' defined in class path resource [config.xml]; nested exception is java.lang.ClassNotFoundException: MessagePrinterService
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [MessagePrinterService] for bean with name 'messageService' defined in class path resource [config.xml]; nested exception is java.lang.ClassNotFoundException: MessagePrinterService
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'printer' defined in class path resource [config.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#c273d3' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#c273d3': Cannot create inner bean '(inner bean)#1423665' of type [org.springframework.aop.config.MethodLocatingFactoryBean] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1423665': Initialization of bean failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [MessagePrinterService] for bean with name 'messageService' defined in class path resource [config.xml]; nested exception is java.lang.ClassNotFoundException: MessagePrinterService
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [MessagePrinterService] for bean with name 'messageService' defined in class path resource [config.xml]; nested exception is java.lang.ClassNotFoundException: MessagePrinterService
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:479)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
Xml config:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="printer" class="helloword.MessagePrinter">
<constructor-arg ref="message"></constructor-arg>
</bean>
<bean id="message" class="helloword.HelloWordMessage">
<constructor-arg value="Hello Spring World!"></constructor-arg>
</bean>
<bean id="messageService" class="MessagePrinterService">
</bean>
<aop:config>
<aop:aspect ref="messageService">
<aop:pointcut id="print" expression="execution(* *.print(..))"/>
<aop:before pointcut-ref="print" method="preMsg"/>
<aop:after pointcut-ref="print" method="postMsg"/>
</aop:aspect>
</aop:config>
</beans>
Classes, all is separate files:
public class HelloWordMessage implements Message{
private String msg;
public HelloWordMessage(String s) {
msg = s;
}
#Override
public String getText() {
return msg;
}
}
public class MessagePrinter implements Printer {
private Message msg;
public MessagePrinter(Message m){
msg = m;
}
#Override
public void print(){
System.out.println(msg.getText());
}
}
public class MessagePrinterService {
public MessagePrinterService(){
System.out.println("MessagePrinterService created");
}
public void preMsg(){
System.out.println("Message alert!:");
}
public void postMsg(){
System.out.println("End of message.");
}
}
public class Aplication {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.print();
context.close();
}
}
java.lang.ClassNotFoundException: MessagePrinterService
Spring cannot load the class MessagePrinterService.
Put it into a specific package and change the configuration accordingly. It should work then.

Instantiation of bean failed : Specified class is an interface

I am facing an issue while creating a bean for dependency injection. Here is the scenario.
I am dealing with MongoDB repository, I have also created a class which uses it. I am trying to instantiate bean instance of both.
MongoDB reporsitory:
#Repository
public interface ProductGlobalTrendRepository extends MongoRepository<ProductGlobalTrend,String>{
public ProductGlobalTrend findByPid(#Param("pId") String pId);
}
The class which is using it:
#Service
#Scope("singleton")
public class ProductTrendService {
#Autowired
#Qualifier("productGlobalTrendRepo")
ProductGlobalTrendRepository productGlobalTrendRepo;
public ProductTrendService() {
super();
}
public void setProductGlobalTrendRepo(
ProductGlobalTrendRepository productGlobalTrendRepo) {
this.productGlobalTrendRepo = productGlobalTrendRepo;
}
public ProductTrendService(ProductGlobalTrendRepository productGlobalTrendRepo) {
super();
this.productGlobalTrendRepo = productGlobalTrendRepo;
}
}
The spring's bean config xml has these entries:
<bean id="productTrendService" class="com.api.services.ProductTrendService"> </bean>
<bean id="productGlobalTrendRepo" class="com.mongodb.repository.ProductGlobalTrendRepository"> </bean>
Following is the error I am getting:
19428 [localhost-startStop-1] WARN
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
- Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'productTrendService': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.mongodb.repository.ProductGlobalTrendRepository
com.api.services.ProductTrendService.productGlobalTrendRepo; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'productGlobalTrendRepo' defined in
class path resource [com/vstore/conf/spring-security.xml]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.mongodb.repository.ProductGlobalTrendRepository]:
Specified class is an interface
It complains that repository is a interface class.
Can somebody please suggest a fix/workaround for this bean dependency injection ?
The problem is with the following information in your context file
<bean id="productGlobalTrendRepo"
class="com.mongodb.repository.ProductGlobalTrendRepository">
</bean>
You should create a class com.mongodb.repository.ProductGlobalTrendRepositoryImpl which implements com.mongodb.repository.ProductGlobalTrendRepository and provides implementation of its methods.
then change your bean declaration info as
<bean id="productGlobalTrendRepo"
class="com.mongodb.repository.ProductGlobalTrendRepositoryImpl">
</bean>
Behind the scene the object is created which is not possible with the interface.

Resources