NullPointerException from ibatis when using FactoryBeanPostProcessor - spring

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)

Related

Error creating bean with name 'embeddedKafka': Invocation of init method failed; nested exception is kafka.common.KafkaException:

I am using the spring cloud contrat to test a kafkaListsener of my service. I use EmbeddedKafka together with the spring cloud contract.
The listener in my service is implemeneted by #KafkaListener from spring kafka.
The contract test I have is like below:
#EmbeddedKafka
#SpringBootTest(classes = {ServiceApplication.class},
properties = {"stubrunner.kafka.enabled=true",
"stubrunner.stream.enabled=false",
"spring.cloud.stream.function.autodetect=false"})
public class EventContractTest {
#Autowired
private StubTrigger stubTrigger;
#SpyBean
#Qualifier("KafkaEventListener")
private EventListener eventListener;
#BeforeEach
public void setup() throws ExecutionException, InterruptedException {
Mockito.doNothing().when(eventListener).onEventReceived(any(), any());
}
#Test
public void kafkaEventTest() throws ExecutionException, InterruptedException {
stubTrigger.trigger("kafka-event");
ArgumentCaptor<Event> eventArgumentCaptor = ArgumentCaptor.forClass(Event.class);
ArgumentCaptor<Bytes> headerArgumentCaptor = ArgumentCaptor.forClass(Bytes.class);
verify(eventListener, timeout(5000).times(1)).
onEventReceived(eventArgumentCaptor.capture(), headerArgumentCaptor.capture());
....
}
#Test
public void kafkaEventTest2() throws ExecutionException, InterruptedException {
stubTrigger.trigger("kafka-event-2");
ArgumentCaptor<Event> eventArgumentCaptor = ArgumentCaptor.forClass(Event.class);
ArgumentCaptor<Bytes> headerArgumentCaptor = ArgumentCaptor.forClass(Bytes.class);
verify(eventListener, timeout(5000).times(1)).
onEventReceived(eventArgumentCaptor.capture(), headerArgumentCaptor.capture());
....
}
}
when run the tests case, in most cases it will pass, but it will randomlly fail with the following exception:
givenEventFromContract_whenCancelSubscription_thenTriggerSubscriptionChangedKafkaEvent
Time elapsed: 0.002 s <<< ERROR! 14:12:43
java.lang.IllegalStateException: Failed to load ApplicationContext
14:12:43 Caused by:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'embeddedKafka': Invocation of init method
failed; nested exception is kafka.common.KafkaException: 14:12:43
Caused by: kafka.common.KafkaException: 14:12:43 Caused by:
java.util.concurrent.TimeoutException 14:12:43 14:12:43 [ERROR]
givenEventFromContract_whenDeleteSubscription_thenTriggerSubscriptionDeletedKafkaEvent
Time elapsed: 25.891 s <<< ERROR! 14:12:43
java.lang.IllegalStateException: java.util.concurrent.TimeoutException
14:12:43 at
And below are my kafka relevant configuration:
# -- Kafka with PLAINTEXT authentication --
com.sap.kafka.enabled=false
spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}
spring.kafka.consumer.group-id=test
spring.kafka.consumer.properties.auto.offset.reset=earliest
spring.kafka.topics.default.replication-factor=1
spring.kafka.topics.default.partition-count=1
spring.kafka.topics.default.min-in-sync-replicas=1
Does someone know what was the issue? is this a bug of spring kafka?

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?

Spring throwing Circular Reference Error with ObjectMapper and RepositoryRestMvcConfiguration

I have a Spring Boot application (2.0.3) that's throwing a circular reference error involving objectMapper (faster.xml Jackson implementation, 2.9.6). It builds fine with Gradle (4.10.2), but upon deployment throws the following error:
...; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.leroyjenkins.service.common.config.CommonConfig':
Unsatisfied dependency expressed through field 'objectMappers'; nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'objectMapper' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.fasterxml.jackson.databind.ObjectMapper]:
Circular reference involving containing bean 'org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration' -
consider declaring the factory method as static for independence from its containing instance. Factory method 'objectMapper' threw exception; nested exception is java.lang.NullPointerException",
"\tat org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)",
The CommonConfig is referring to a configuration file I have:
#Configuration
#EnableHypermediaSupport(type = .
EnableHypermediaSupport.HypermediaType.HAL)
#EnableScheduling
#Order(Ordered.LOWEST_PRECEDENCE)
#CompileStatic
#Slf4j
#Slf4jPlusMetrics("mlog")
class CommonConfig {
...
#Autowired List<ObjectMapper> objectMappers
#PostConstruct
void afterPropertiesSet() {
log.info("initializing CommonConfig objectMappersSize={},contextPath={},threadPoolSize={},threadPoolQueueCapacity={},threadPoolDefaultTimeout={},appName={}",
objectMappers.size(), contextPath, threadPoolSize, threadPoolQueueCapacity, threadPoolDefaultTimeout, appName)
objectMappers.each { ObjectMapper objectMapper ->
objectMapper.enable(SerializationFeature.INDENT_OUTPUT)
objectMapper.registerModule(new ParameterNamesModule())
objectMapper.registerModule(new Jdk8Module())
objectMapper.registerModule(new JavaTimeModule())
objectMapper.registerModule(new JodaModule())
objectMapper.registerModule(new GsnModelJacksonModule())
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
}
}
...
}
We just updated to jdk11...not sure if that's relevant here.

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)

Spring MVC no default constructor found

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 >

Resources