Class loading error on websphere when upgrading to Spring 4.2.3 - spring

When I upgrade a multi-war Spring application from Spring 4.1.8 to 4.2.3 I get a strange ClassNotFoundException in a websphere application server (version 8.5.5). The class that is not found by the classloader is on the classpath and was found with previous releases of Spring.
[11.12.15 10:04:27:536 CET] 0000004f FfdcProvider W com.ibm.ws.ffdc.impl.FfdcProvider logIncident FFDC1003I: FFDC Incident emitted on D:\devsbb\websphere\was8_5\IBM\WebSphere\AppServer\profiles\AppSrv01\logs\ffdc\server1_bc0c2481_15.12.11_10.04.27.4771875357035970693584.txt com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated 1341
[11.12.15 10:04:27:536 CET] 0000004f webapp E com.ibm.ws.webcontainer.webapp.WebApp notifyServletContextCreated SRVE0283E: Exception caught while initializing context: {0}
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'showCaseViewModel' defined in BeanDefinition defined in file [D:\devsbb\websphere\was8_5\IBM\WebSphere\AppServer\profiles\AppSrv01\installedApps\localhostNode01Cell\template-ear-4.0.3-SNAPSHOT.ear\template-web-jsf.war\WEB-INF\classes\ch\sbb\myapp\presentation\ShowCaseViewModel.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
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)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:1689)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:414)
at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88)
at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:169)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:749)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:634)
at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:426)
at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:718)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1177)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1370)
at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:639)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:968)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:776)
at com.ibm.ws.runtime.component.ApplicationMgrImpl$5.run(ApplicationMgrImpl.java:2195)
at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5474)
at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5600)
at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2200)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:389)
at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:332)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:119)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$CUInitializer.run(CompositionUnitMgrImpl.java:938)
at com.ibm.wsspi.runtime.component.WsComponentImpl$_AsynchInitializer.run(WsComponentImpl.java:502)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1864)
Caused by: org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:218)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
at org.springframework.aop.scope.ScopedProxyFactoryBean.setBeanFactory(ScopedProxyFactoryBean.java:111)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1565)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
... 36 more
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException
at org.springframework.asm.ClassWriter.getCommonSuperClass(ClassWriter.java:1684)
at org.springframework.asm.ClassWriter.getMergedType(ClassWriter.java:1654)
at org.springframework.asm.Frame.merge(Frame.java:1426)
at org.springframework.asm.Frame.merge(Frame.java:1337)
at org.springframework.asm.MethodWriter.visitMaxs(MethodWriter.java:1475)
at org.springframework.cglib.core.CodeEmitter.visitMaxs(CodeEmitter.java:842)
at org.springframework.cglib.transform.impl.UndeclaredThrowableTransformer$1.visitMaxs(UndeclaredThrowableTransformer.java:56)
at org.springframework.cglib.core.CodeEmitter.visitMaxs(CodeEmitter.java:842)
at org.springframework.cglib.core.CodeEmitter.end_method(CodeEmitter.java:138)
at org.springframework.cglib.proxy.MethodInterceptorGenerator.generate(MethodInterceptorGenerator.java:131)
at org.springframework.cglib.proxy.Enhancer.emitMethods(Enhancer.java:1005)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:509)
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:231)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:55)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:202)
... 41 more
Here is my class:
package ch.sbb.myapp.presentation;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.sbb.esta.core.stereotype.Scope;
import ch.sbb.esta.core.stereotype.web.EstaViewModel;
import ch.sbb.esta.core.type.Email;
import ch.sbb.myapp.exception.TemplateErrorCode;
import ch.sbb.myapp.model.Customer;
import ch.sbb.myapp.model.CustomerStatus;
import ch.sbb.myapp.model.i18n.I18nMessageKey;
import ch.sbb.myapp.presentation.exception.SampleTranslateableFileCopyException;
/**
* ViewModel für den Primefaces Showcase.
*/
#EstaViewModel(scope = Scope.REQUEST)
public class ShowCaseViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ShowCaseViewModel.class);
public boolean isMcaIntegrationInClasspath() {
try {
this.getClass().getClassLoader().loadClass("ch.sbb.myapp.presentation.McaDemoViewModel");
return true;
} catch (ClassNotFoundException e) { // NOSONAR: is just a check whether MCA integration is on the classpath
return false;
}
}
public CustomerStatus getCustomerStatusNull() {
return null;
}
public void setCustomerStatusNull(CustomerStatus t) {
}
public CustomerStatus getCustomerStatus() {
return CustomerStatus.VIP;
}
public void throwEstaException() throws SampleTranslateableFileCopyException {
throw new SampleTranslateableFileCopyException(I18nMessageKey.ERROR_WHILE_CALLING_SERVICE,
TemplateErrorCode.FILE_COPY_ERROR_CODE, "fileA", "fileB");
}
public void logValidationException() {
Customer wrongCustomer = new Customer("fi", "la", new Email("bla#sbb.ch"));
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Customer>> violations = validator.validate(wrongCustomer);
Set<ConstraintViolation<?>> violationsWithoutType = new HashSet<>();
violationsWithoutType.addAll(violations);
LOGGER.warn("violated exception", new ConstraintViolationException("bla", violationsWithoutType));
}
}
The annotation #EstaViewModel is declared as a simple #Component:
#Inherited
#Component
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.TYPE })
public #interface EstaViewModel {
String value() default "";
Scope scope() default Scope.REQUEST;
}
All other classes with the #EstaViewModel annotation are initialized without any problem.
Any ideas?

Related

how to fix the error "error creating bean with name...."

when I run my application there is the following error displayed:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pamdaBatchConfigurer': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getJobRepository' defined in com.orange.pamda.config.PamdaBatchConfigurer: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.repository.JobRepository]: Circular reference involving containing bean 'pamdaBatchConfigurer' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getJobRepository' threw exception; nested exception is java.lang.IllegalArgumentException: DatabaseType not found for product name: [MariaDB]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
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)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4685)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5146)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:343)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:474)
here is my file "pamdabatchconfigurer.java":
package com.orange.pamda.config;
import java.util.Date;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.JobExplorerFactoryBean;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import com.orange.pamda.config.batch.listener.SendFileAfterExportListener;
import com.orange.pamda.worker.config.CatalogueExporterJobConfiguration;
import com.orange.pamda.worker.config.CatalogueImporterJobConfiguration;
import com.orange.pamda.worker.config.CommonJobConfiguration;
import com.orange.pamda.worker.config.DataExporterJobConfiguration;
import com.orange.pamda.worker.config.HierarchyValidatorJobConfiguration;
import com.orange.pamda.worker.config.JobBuilderFactory;
import com.orange.pamda.worker.config.KoalaExporterJobConfiguration;
import com.orange.pamda.worker.config.MappingExporterJobConfiguration;
import com.orange.pamda.worker.config.MappingImporterJobConfiguration;
import com.orange.pamda.worker.config.OrphanExporterJobConfiguration;
import com.orange.pamda.worker.config.ReleaseJobConfiguration;
import com.orange.pamda.worker.config.SummaryExporterJobConfiguration;
#Configuration
#EnableBatchProcessing(modular = true)
#Import({ CommonJobConfiguration.class, CatalogueExporterJobConfiguration.class,
CatalogueImporterJobConfiguration.class, DataExporterJobConfiguration.class,
HierarchyValidatorJobConfiguration.class, KoalaExporterJobConfiguration.class,
MappingExporterJobConfiguration.class, MappingImporterJobConfiguration.class,
OrphanExporterJobConfiguration.class, ReleaseJobConfiguration.class, SummaryExporterJobConfiguration.class })
public class PamdaBatchConfigurer implements BatchConfigurer {
#Autowired
private PlatformTransactionManager transactionManager;
#Autowired
private DataSource dataSource;
#Override
#Bean
public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
jobRepositoryFactoryBean.setDataSource(dataSource);
jobRepositoryFactoryBean.setTransactionManager(transactionManager);
jobRepositoryFactoryBean.setIsolationLevelForCreate("ISOLATION_DEFAULT");
jobRepositoryFactoryBean.afterPropertiesSet();
return jobRepositoryFactoryBean.getObject();
}
#Override
public PlatformTransactionManager getTransactionManager() throws Exception {
return transactionManager;
}
#Override
#Bean
public JobLauncher getJobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(getJobRepository());
// jobLauncher.setTaskExecutor(getTaskExecutor());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
#Override
#Bean
public JobExplorer getJobExplorer() throws Exception {
JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
jobExplorerFactoryBean.setDataSource(dataSource);
jobExplorerFactoryBean.afterPropertiesSet();
return jobExplorerFactoryBean.getObject();
}
// #Bean
// public TaskExecutor getTaskExecutor() {
// SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new
// SimpleAsyncTaskExecutor();
// simpleAsyncTaskExecutor.setConcurrencyLimit(1000); // no throttle
// return simpleAsyncTaskExecutor;
// }
#Bean
public JobBuilderFactory getJobBuilderFactory() throws Exception {
return new JobBuilderFactory(getJobRepository(), sendFileAfterExportListener());
}
#Bean
public StepBuilderFactory getStepBuilderFactory() throws Exception {
return new StepBuilderFactory(getJobRepository(), transactionManager);
}
#Bean
public SendFileAfterExportListener sendFileAfterExportListener() {
return new SendFileAfterExportListener();
}
#PostConstruct
#Transactional
public void init() throws Exception {
JobExplorer jobExplorer = getJobExplorer();
JobRepository jobRepository = getJobRepository();
for (String jobName : jobExplorer.getJobNames()) {
Set<JobExecution> runningJobExecutions = jobExplorer.findRunningJobExecutions(jobName);
for (JobExecution runningJobExecution : runningJobExecutions) {
runningJobExecution.setExitStatus(ExitStatus.UNKNOWN);
runningJobExecution.setEndTime(new Date());
jobRepository.update(runningJobExecution);
}
}
}
}
I really do not know where this error comes from can someone help me please?
Most important part of the stacktrace: DatabaseType not found for product name: [MariaDB]
Look here: https://github.com/spring-projects/spring-framework/issues/22344
Similar issues:
DatabaseType not found for product name: [Impala]
Spring batch --- DatabaseType not found for product name: [Informix Dynamic Server]
Could you please check this part of the exception, that you have added. It might be the reason : "Circular reference involving".
Circular reference involving containing bean 'pamdaBatchConfigurer' -
consider declaring the factory method as static for independence from
its containing instance.

Spring Boot Filter error, Failed to register after unregistered Filter

Im both new to Spring Boot and Kotlin.
I'm having an error saying that
Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException:
Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
2018-10-03 15:50:21.601 ERROR 63436 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
at com.jxinternet.platform.ms.merchant.MerchantApplicationKt.main(MerchantApplication.kt:28)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
... 20 common frames omitted
Caused by: java.lang.IllegalArgumentException: Cannot register after unregistered Filter class com.jxinternet.platform.ms.merchant.config.security.ReplaceResponseFilter
at org.springframework.security.config.annotation.web.builders.FilterComparator.registerAfter(FilterComparator.java:156)
at org.springframework.security.config.annotation.web.builders.HttpSecurity.addFilterAfter(HttpSecurity.java:1121)
at com.jxinternet.platform.ms.merchant.config.security.WebSecurityConfig.configure(WebSecurityConfig.kt:64)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:230)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:321)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:92)
at com.jxinternet.platform.ms.merchant.config.security.WebSecurityConfig$$EnhancerBySpringCGLIB$$7e2d609b.init(<generated>)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c.CGLIB$springSecurityFilterChain$3(<generated>)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c$$FastClassBySpringCGLIB$$d83091e8.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$f5effa1c.springSecurityFilterChain(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 21 common frames omitted
Disconnected from the target VM, address: '127.0.0.1:51914', transport: 'socket'
Process finished with exit code 1
my ReplaceResponseFilter.kt
package com.jxinternet.platform.ms.merchant.config.security
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.Order
import org.springframework.hateoas.VndErrors
import org.springframework.http.HttpStatus
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.GenericFilterBean
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponseWrapper
open class ReplaceResponseFilter : Filter {
companion object {
private val log = LoggerFactory.getLogger(ReplaceResponseFilter::class.java)
}
override fun doFilter(request: ServletRequest, response: ServletResponse, filterChain: FilterChain) {
val t = response as HttpServletResponseWrapper
}
override fun init(p0: FilterConfig?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun destroy(){
}
}
my WebSecurityConfig.kt
package com.jxinternet.platform.ms.merchant.config.security
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.firewall.HttpFirewall
import org.springframework.security.web.firewall.StrictHttpFirewall
#Configuration
#EnableWebSecurity
class WebSecurityConfig(
private val tokenAuthenticationService: TokenAuthenticationService,
private val objectMapper: ObjectMapper
) : WebSecurityConfigurerAdapter() {
// 防止防止url带两个// spring security 5会有问题 所以必须放开这个配置
#Bean
fun allowUrlEncodedSlashHttpFirewall(): HttpFirewall {
val firewall = StrictHttpFirewall()
firewall.setAllowUrlEncodedSlash(true)
return firewall
}
override fun configure(web: WebSecurity) {
super.configure(web)
web.httpFirewall(allowUrlEncodedSlashHttpFirewall())
}
// 设置 HTTP 验证规则
override fun configure(http: HttpSecurity) {
// 关闭csrf验证
http.csrf().disable()
// 对请求进行认证
.authorizeRequests()
// 所有 / 的所有请求 都放行
.antMatchers(
"/",
"/pay/**",
"/scan/**",
"/login",
"/actuator/health",
"/webjars/springfox-swagger-ui/**",
"/swagger-ui.html",
"/configuration/ui",
"/swagger-resources",
"/v2/api-docs",
"/swagger-resources/**").permitAll()
// 所有 /login 的POST请求 都放行
// 所有请求需要身份认证
.anyRequest().authenticated()
.and()
// 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容
//.addFilterBefore(loginFilter(objectMapper, tokenAuthenticationService), UsernamePasswordAuthenticationFilter::class.java)
// 添加一个过滤器验证其他请求的Token是否合法
.addFilterBefore(JWTAuthenticationFilter(tokenAuthenticationService, objectMapper), UsernamePasswordAuthenticationFilter::class.java)
.addFilterAfter(ReplaceResponseFilter(), ReplaceResponseFilter::class.java)
// 设置session无状态!!
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}
}
In ReplaceResponseFilter, you're missing:
filterChain.doFilter(request, response)
Otherwise, your filter chain cannot continue.
I also believe that this is incorrect:
.addFilterAfter(ReplaceResponseFilter(), ReplaceResponseFilter::class.java)
As far as I understand your code, that filter should come after JWTAuthenticationFilter. Therefore:
.addFilterAfter(ReplaceResponseFilter(), JWTAuthenticationFilter::class.java)

Using #DataJpaTest when multiple datasources are configured [duplicate]

This question already has answers here:
Using #DataJpaTest with multiple DataSource and custom repository implementation [duplicate]
how to use #DataJpaTest with multiple datasourse
(3 answers)
Closed 4 years ago.
My application is configured with two datasources, following this example: https://github.com/snicoll-demos/demo-multi-entity-managers
Everything works when running the app, but when I try to add a #DataJpaTest, it isn't able to load the application context:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/example/reports/ws/MainDatabaseConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'mainEntityManager' threw exception; nested exception is java.lang.IllegalArgumentException: No visible constructors in class org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
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)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 49 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'mainEntityManager' threw exception; nested exception is java.lang.IllegalArgumentException: No visible constructors in class org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 66 more
Caused by: java.lang.IllegalArgumentException: No visible constructors in class org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean
at org.springframework.cglib.proxy.Enhancer.filterConstructors(Enhancer.java:666)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:567)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:329)
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:337)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.createCglibProxyForFactoryBean(ConfigurationClassEnhancer.java:531)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.enhanceFactoryBean(ConfigurationClassEnhancer.java:502)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:340)
at com.example.reports.ws.MainDatabaseConfig$$EnhancerBySpringCGLIB$$22c681c6.mainDataSource(<generated>)
at com.example.reports.ws.MainDatabaseConfig.mainEntityManager(MainDatabaseConfig.java:59)
at com.example.reports.ws.MainDatabaseConfig$$EnhancerBySpringCGLIB$$22c681c6.CGLIB$mainEntityManager$2(<generated>)
at com.example.reports.ws.MainDatabaseConfig$$EnhancerBySpringCGLIB$$22c681c6$$FastClassBySpringCGLIB$$c8213502.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
at com.example.reports.ws.MainDatabaseConfig$$EnhancerBySpringCGLIB$$22c681c6.mainEntityManager(<generated>)
Anyone know what I need to do to get Spring's magic working in this setup?
The configuration for my main database:
package com.example.reports.ws;
import javax.persistence.EntityManagerFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.example.reports.ws.model.ReportDefinition;
import com.example.reports.ws.repos.ChartPrefsRepository;
import com.example.reports.ws.svc.ChartService;
#Configuration
#EntityScan
#EnableTransactionManagement()
#EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "mainTransactionManager", basePackages = "com.example.reports.ws.repos")
public class MainDatabaseConfig {
#Autowired
private Environment env;
#Autowired(required = false)
private PersistenceUnitManager persistenceUnitManager;
#Bean
#ConfigurationProperties("app.main.jpa")
public JpaProperties mainJpaProperties() {
return new JpaProperties();
}
#Bean
#Primary
#ConfigurationProperties(prefix = "app.main.datasource")
public DataSource mainDataSource() {
return (DataSource) DataSourceBuilder.create().type(DataSource.class).build();
}
#Bean(name = "entityManagerFactory")
#Primary
public LocalContainerEntityManagerFactoryBean mainEntityManager(JpaProperties mainJpaProperties) {
EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(mainJpaProperties);
return builder.dataSource(mainDataSource())
.packages(ReportDefinition.class, ChartPrefsRepository.class, ChartService.class)
.persistenceUnit("mainDs").build();
}
private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties mainJpaProperties) {
JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(mainJpaProperties);
return new EntityManagerFactoryBuilder(jpaVendorAdapter, mainJpaProperties.getProperties(),
this.persistenceUnitManager);
}
private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) {
AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(jpaProperties.isShowSql());
adapter.setDatabase(jpaProperties.getDatabase());
adapter.setDatabasePlatform(jpaProperties.getDatabasePlatform());
adapter.setGenerateDdl(jpaProperties.isGenerateDdl());
return adapter;
}
#Bean
#Primary
public PlatformTransactionManager mainTransactionManager(EntityManagerFactory mainEntityManager) {
return new JpaTransactionManager(mainEntityManager);
}
}

Error creating bean with name 'endpoint' in spring 4

I created a JAX-WS application with spring (4.2.4), spring boot (1.3.1) and apache cxf (3.1.4). While running the application in apache server 8, i am getting below error:
2015-12-24 16:15:35.767 INFO 3956 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'errorPageFilter' to: [/*]
2015-12-24 16:15:36.120 WARN 3956 --- [ost-startStop-1] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpoint' defined in com.pd.config.PDConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.xml.ws.Endpoint]: Factory method 'endpoint' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pd.webService.response.model.ResponseModel com.pd.webService.Impl.ServiceInterfaceImpl.responseModel; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pd.webService.response.model.ResponseModel] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2015-12-24 16:15:36.135 ERROR 3956 --- [ost-startStop-1] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpoint' defined in com.pd.config.PDConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.xml.ws.Endpoint]: Factory method 'endpoint' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pd.webService.response.model.ResponseModel com.pd.webService.Impl.ServiceInterfaceImpl.responseModel; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pd.webService.response.model.ResponseModel] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.context.web.SpringBootServletInitializer.run(SpringBootServletInitializer.java:149) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:129) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:85) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175) [spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5151) [catalina.jar:8.0.20]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.0.20]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) [catalina.jar:8.0.20]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) [catalina.jar:8.0.20]
at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_60]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_60]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.xml.ws.Endpoint]: Factory method 'endpoint' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pd.webService.response.model.ResponseModel com.pd.webService.Impl.ServiceInterfaceImpl.responseModel; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pd.webService.response.model.ResponseModel] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
... 27 common frames omitted
Below given the configuration:
package com.pd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
PDConfig:
package com.pd.config;
import javax.xml.ws.Endpoint;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.ws.config.annotation.EnableWs;
import com.pd.webService.ServiceInterface;
import com.pd.webService.Impl.ServiceInterfaceImpl;
#EnableWs
#Configuration
public class PDConfig extends SpringBootServletInitializer {
#Bean
public ServletRegistrationBean dispatcherServlet() {
CXFServlet cxfServlet = new CXFServlet();
return new ServletRegistrationBean(cxfServlet, "/service/*");
}
#Bean(name="cxf")
public SpringBus springBus() {
return new SpringBus();
}
#Bean
public ServiceInterface myService() {
return new ServiceInterfaceImpl();
}
#Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), myService());
endpoint.publish("/serviceinterface");
return endpoint;
}
#Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
container.addErrorPages(error401Page, error404Page, error500Page);
}
};
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
PDInitializer:
package com.pd.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class PDInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { PDConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
cxf-beans.xml:
<?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:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint id="serviceinterface" implementor="com.pd.webService.Impl.ServiceInterfaceImpl"
wsdlLocation="wsdl/serviceinterfaceimpl.wsdl" address="/ServiceInterfaceImplPort">
<jaxws:features>
<bean class="org.apache.cxf.feature.LoggingFeature" />
</jaxws:features>
</jaxws:endpoint>
</beans>
My service implementation:
package com.pd.webService.Impl;
import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.pd.webService.ServiceInterface;
import com.pd.webService.request.model.UserModel;
import com.pd.webService.response.model.ResponseModel;
#Component
#WebService(endpointInterface="com.pd.webService.ServiceInterface")
public class ServiceInterfaceImpl extends SpringBeanAutowiringSupport implements ServiceInterface {
#Autowired
ResponseModel responseModel;
#Override
public ResponseModel getUserInfo(UserModel userModel) {
responseModel.setUserName(userModel.getUserName());
responseModel.setAge(25);
responseModel.setCompany("MINDTREE");
responseModel.setExperience("2.8 years");
return responseModel;
}
}
Response Model:
package com.pd.webService.response.model;
import org.springframework.stereotype.Component;
#Component
public class ResponseModel {
private String userName;
private int age;
private String company;
private String experience;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
}
Could you please help me with this. Thanks in advance.
In the myService bean you have autowired filed of type ResponseModel.
You have to declare a bean of that type.
Something like this:
#Bean
public ResponseModel responseModel() {
return new ResponseModel();
}
Looks like when you extend SpringBeanAutowiringSupport that bean gets loaded befor the other beans in the spring container. You don't need that - remove extends SpringBeanAutowiringSupport from class ServiceInterfaceImpl

Adding custom behavior to all repositories without xml configuration

I am trying to add custom behavior to all repositories in my spring application but I don't want to use XML configuration, only spring annotation like #xxxx.
So I looked for that on the Internet and I found this documentation.
The problem with the documentation is that it deals with JPA (not MongoDB) and the step 4 is not specific enough for a spring application without xml annotation.
Documentation step 4 :
declare beans of the custom factory directly
How we do that?
So I didn't give up and I looked deeper on the Internet and I found this.
But this time, it was for Solr (not Mongo).
The interesting part is:
import org.springframework.context.annotation.Configuration;
import org.springframework.data.solr.repository.config.EnableSolrRepositories;
#Configuration
#EnableSolrRepositories(
basePackages = "net.petrikainulainen.spring.datasolr.todo.repository.solr",
repositoryFactoryBeanClass = CustomSolrRepositoryFactoryBean.class
)
public class SolrContext {
//Configuration is omitted.
}
But my application still does not work! You can find all the code in github.
Architecture
src/main/java
fr.exemple.test.Application.java
fr.exemple.test.controller.TestController.java
fr.exemple.test.model.domain.Test.java
fr.exemple.test.model.repository.TestRepository.java
fr.exemple.test.model.repository.global.MyRepository.java
fr.exemple.test.model.repository.global.MyRepositoryFactoryBean.java
fr.exemple.test.model.repository.global.MyRepositoryImpl.java
My Code
Application :
package fr.exemple.test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import fr.exemple.test.model.repository.global.MyRepositoryFactoryBean;
#Configuration
#ComponentScan
#EnableAutoConfiguration
#EnableMongoRepositories(
basePackages = {"fr.exemple.test.repository.global"},
repositoryFactoryBeanClass = MyRepositoryFactoryBean.class
)
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
app.run(args);
}
}
TestController :
package fr.exemple.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import fr.exemple.test.model.repository.TestRepository;
#RestController
#RequestMapping("/test")
public class TestController {
#Autowired
private TestRepository repository;
#RequestMapping(method=RequestMethod.GET)
public void sharedCustomMethodTest() {
repository.sharedCustomMethod("Hello World !");
}
}
Test :
package fr.exemple.test.model.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Test {
#Id
private String id;
private String firstName;
private String lastName;
public Test() {}
public Test(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
TestRepository :
package fr.exemple.test.model.repository;
import fr.exemple.test.model.domain.Test;
import fr.exemple.test.model.repository.global.MyRepository;
public interface TestRepository extends MyRepository<Test, String> {
}
MyRepository :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.NoRepositoryBean;
#NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends MongoRepository<T, ID>{
void sharedCustomMethod(ID id);
}
MyRepositoryFactoryBean :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
public class MyRepositoryFactoryBean<R extends MongoRepository<T, I>, T, I extends Serializable>
extends MongoRepositoryFactoryBean<R, T, I> {
#Override
protected RepositoryFactorySupport getFactoryInstance(MongoOperations operations) {
return new MyRepositoryFactory<T, I>(operations);
}
private static class MyRepositoryFactory<T, I extends Serializable> extends
MongoRepositoryFactory {
private MongoOperations mongoOperations;
public MyRepositoryFactory(MongoOperations mongoOperations) {
super(mongoOperations);
this.mongoOperations = mongoOperations;
}
protected Object getTargetRepository(RepositoryMetadata metadata) {
TypeInformation<T> information = ClassTypeInformation.from((Class<T>)metadata.getDomainType());
MongoPersistentEntity<T> pe = new BasicMongoPersistentEntity<T>(information);
MongoEntityInformation<T,I> mongometa = new MappingMongoEntityInformation<T, I>(pe);
return new MyRepositoryImpl<T, I>(mongometa, mongoOperations);
}
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return MyRepository.class;
}
}
}
MyRepositoryImpl :
package fr.exemple.test.model.repository.global;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;
public class MyRepositoryImpl<T, ID extends Serializable> extends
SimpleMongoRepository<T, ID> implements MyRepository<T, ID> {
private Log log = LogFactory.getLog(MyRepositoryImpl.class);
private MongoOperations mongoOperations;
public MyRepositoryImpl(MongoEntityInformation<T, ID> metadata,
MongoOperations mongoOperations) {
super(metadata, mongoOperations);
this.mongoOperations = mongoOperations;
}
#Override
public void sharedCustomMethod(ID id) {
log.info(id);
}
}
Stack Trace
Error starting ApplicationContext. To display the auto-configuration report enabled debug logging (start with --debug)
2014-07-13 11:12:51.951 ERROR 2144 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at fr.exemple.test.Application.main(Application.java:23)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 14 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 16 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:82)
at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:52)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:128)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 26 common frames omitted
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at fr.exemple.test.Application.main(Application.java:23)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private fr.exemple.test.model.repository.TestRepository fr.exemple.test.controller.TestController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 14 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 16 more
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property shared found for type void!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:213)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:321)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:301)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:82)
at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:52)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:128)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:320)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:169)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:224)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:210)
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 26 more
This happens as the package structure is not consistent. The base package of #EnableMongoRepositories points to fr.exemple.test.repository.global whereas the repository definition is located in fr.exemple.test.model.repository. As the scan for repositories returns without any result boot auto configuration, at this point not knowing of any custom RepositoryFactoryBean definitions, kicks in, enabling repositories on fr.exemple.test where Application resides.
So you could update your package structure.
Or make boot aware of MyRepositoryFactoryBean by registering it in your context via #Component and remove #EnableMongoRepositories so that scanning for a bean of type RepositoryFactoryBeanSupport can pick up the config.
When you declare #EnableMongoRepositories please take a look at availables options. One of them is :
public abstract Class<?> repositoryFactoryBeanClass
Returns the FactoryBean class to be used for each repository instance.
Defaults to MongoRepositoryFactoryBean.
Returns:
Default:
org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.class
so i.e
#EnableMongoRepositories(repositoryFactoryBeanClass=YourMongoCustomRepositoryFactoryBean.class)

Resources