Spring MVC no default constructor found - spring

I've got a problem with this program
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cdmiService': Cannot resolve reference to bean 'badRequestException' while setting bean property 'providers' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'badRequestException' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.snia.cdmiserver.exception.BadRequestException]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.snia.cdmiserver.exception.BadRequestException.<init>()
and my xml is as follows:
<bean id="badRequestException" class="org.snia.cdmiserver.exception.BadRequestException"/>
The BadRequestException.java is as follows:
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
public BadRequestException(Throwable cause) {
super(cause);
}
How could I solve this problem?add a default construtor or edit the xml file?

How could I solve this problem?add a default construtor or edit the xml file?
You can solve it either way.
add a default construtor:
public BadRequestException() {
super();
}
edit the xml file
<bean id="badRequestException" class="org.snia.cdmiserver.exception.BadRequestException">
<constructor-arg type="java.lang.String"><value>Message you want</value></constructor-arg>
</bean >

Related

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?

NullPointerException from ibatis when using FactoryBeanPostProcessor

I revise some bean definition through a customized BeanFactoryPostProcessor
When the web application startup, it failed:
#Component
public class RPCTimeoutPostProcessor implements BeanFactoryPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(RPCTimeoutPostProcessor.class);
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
overriderThriftTimeoutPolicy(beanFactory);
}
private void overriderThriftTimeoutPolicy(ConfigurableListableBeanFactory beanFactory) {
Map<String, ThriftClientProxy> map = beanFactory.getBeansOfType(ThriftClientProxy.class);
Set<String> keySet = map.keySet();
}
}
[WARNING] Failed startup of context o.m.j.p.JettyWebAppContext
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'baseSystemApi': Unsatisfied dependency
expressed through field 'appConfigService'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'appConfigService': Invocation of init method
failed; nested exception is org.mybatis.spring.MyBatisSystemException:
nested exception is org.apache.ibatis.exceptions.PersistenceException:
Error querying database. Cause: java.lang.NullPointerException The
error may exist in com/xxx/dao/WmAppTextDao.java (best guess) The
error may involve com.xxx.dao.WmAppTextDao.getAll The error occurred
while executing a query Cause: java.lang.NullPointerException at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)

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.

How to autowire mongoTemplate into custom type converter?

I'm trying to create a converter that will fetch object from DB by it's ObjectId. But the mongoTemplate is always empty in converter:
org.springframework.core.convert.ConversionFailedException:
Failed to
convert from type org.bson.types.ObjectId to type
com.atlas.mymodule.datadomain.MyObject for value
'130000000000000000000013';
nested exception is
java.lang.NullPointerException
Code:
#Component
public class ObjectIdToMyObjectConverter implements Converter<ObjectId, MyObject> {
#Autowired
private MongoTemplate mongoTemplate; // null ???
public MyObject convert(ObjectId objectId) {
return mongoTemplate.findById(objectId, MyObject.class); // <- NullPointerException
}
}
Configuration:
#Configuration
#ComponentScan
#EnableMongoRepositories
public abstract class MyModuleConfiguration extends AbstractMongoConfiguration {
#Override
public MongoClient mongo() throws Exception {
List<MongoCredential> mongoCredential = getMongoCredentials();
return mongoCredential == null ?
new MongoClient(getMongoServerAddresses()) :
new MongoClient(getMongoServerAddresses(), mongoCredential, getMongoClientOptions());
}
protected abstract List<MongoCredential> getMongoCredentials();
protected abstract MongoClientOptions getMongoClientOptions();
protected abstract List<ServerAddress> getMongoServerAddresses() throws UnknownHostException;
#Bean
public ObjectIdToMyObjectConverter objectIdToMyObjectConverter() {
return new ObjectIdToMyObjectConverter());
}
#Override
public CustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
converters.add(objectIdToMyObjectConverter());
return new CustomConversions(converters);
}
}
Test Configuration:
public class MyModuleTestConfiguration extends MyModuleConfiguration {
// overrides abstract methods, defines connection details...
}
update:
I've updated the code according to #mavarazy suggestion (added ObjectIdToMyObjectConverter bean definition) but got an exception:
Error creating bean with name 'mongoTemplate': Requested bean is
currently in creation: Is there an unresolvable circular reference?
Full exception:
Error creating bean with name 'mongoTemplate' defined in com.atlas.MyModule.MyModuleTestConfiguration:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mappingMongoConverter' defined in com.atlas.MyModule.MyModuleTestConfiguration: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.mongodb.core.convert.MappingMongoConverter]: Factory method 'mappingMongoConverter' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mongoMappingContext' defined in com.atlas.MyModule.MyModuleTestConfiguration: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.mongodb.core.mapping.MongoMappingContext]: Factory method 'mongoMappingContext' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'customConversions' defined in com.atlas.MyModule.MyModuleTestConfiguration: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.mongodb.core.convert.CustomConversions]: Factory method 'customConversions' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'objectIdToMyObjectConverter': 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.atlas.MyModule.ObjectIdToMyObjectConverter.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?
Thanks.
ObjectIdToMyObjectConverter is not a spring bean. If you want #Autowired to work, create ObjectIdToMyObjectConverter as Spring bean, like this:
#Bean
public ObjectIdToMyObjectConverter objectIdToMyObjectConverter() {
return new ObjectIdToMyObjectConverter());
}
and #Autowire it in your configuration.
Following #Savash update
I have not paid enough attention to your configurations.
What you see is happening because you are trying to create MongoTemplate, which depends on CustomConversions, and at the same time CustomConversions depend on MongoTemplate, spring can't and should not do that.
As a solution:
You can create your CustomConversions with ApplicationContextAware, and extract MongoTemplate reference lazily on a first call.
I thought you are using CustomConversions as part of spring-integration or something. If so it does not need to be part of converters for Mongo. If you need it as MongoConverters, you are doing something really strange.
What is exact use case, you need this for?
Following comments:
Do I understand right, that you want MongoTemplate to read object with user reference as User object, and write object with User value as user reference?
I think.
You have a bad data model (you are trying to emulate JOIN operation in your MongoTemplate, which means you are missing something in your data model, and this is not how you should work with mongo).
Just call User explicitly when you need it, don't overload your DB with additional work, you'll have problems with performance
You can use another object, which you'll enrich with current user, as needed
Maybe SQL & ORM like Hibernate is a better approach for you ?
Try Hibernate OGM for your purpose, it might provide functionality, you need (Not sure, though, have not worked with it)

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