Springboot attach #PersistenceContext EntityManager to a #Bean - java

I am getting following Error:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 4: D1EntityManager,D2EntityManager,BaseEntityManager,oldDbEntityManager
I have declared in different files those 4 EntityManagers following this template:
RepositoryConfigurationTemplate
#Configuration
#EnableJpaRepositories(
basePackages = "...myReposPackages...",
entityManagerFactoryRef = ConfigurationChanges.ENTITY_MANAGER_BEAN_NAME,
transactionManagerRef = ConfigurationChanges.TRANSACTION_MANAGER_BEAN_NAME
)
#ComponentScan("...myScanPackages...")
#EnableConfigurationProperties
public class MyRepoConfigClass {
...
...
public final static String ENTITY_MANAGER_BEAN_NAME = "...EntityManagerSingleConstant..."; // D1EntityManager / D2EntityManager / BaseEntityManager / oldDbEntityManager for different classes
public final static String TRANSACTION_MANAGER_BEAN_NAME = "...TransactionManagerSingleConstant..."; // D1TransactionManager / D2TransactionManager / BaseTransactionManager / oldDbTransactionManager for different classes
#Bean(name=ENTITY_MANAGER_BEAN_NAME)
#Qualifier(ENTITY_MANAGER_BEAN_NAME) // Not sure if this is needed, I just added it trying to make it work
public LocalContainerEntityManagerFactoryBean myClassEntityManager() {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
... initializations ...
em.setDataSource(...myDataSource...)
em.setPackagesToScan("...EntitiesPackagesToScan...")
em.setPersistenceUnitName(ENTITY_MANAGER_BEAN_NAME); // Not sure if this is needed, I just added it trying to make it work
}
#Bean(name=TRANSACTION_MANAGER_BEAN_NAME)
#Qualifier(TRANSACTION_MANAGER_BEAN_NAME) // Not sure if this is needed, I just added it trying to make it work
public PlatformTransactionManager myClassTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
myClassEntityManager().getObject());
return transactionManager;
}
}
And I am trying to reference it from Services like this:
ServiceTemplate
#Service
public class myServiceClass {
#PersistenceContext(unitName = MyRepoConfigClass.ENTITY_MANAGER_BEAN_NAME) // Thought this might be the solution for JPA PersistenceContext, but did not work anyway
#Qualifier(MyRepoConfigClasss.ENTITY_MANAGER_BEAN_NAME) // Not sure if this is supposed to be done like this. In normal spring boot components it works
private EntityManager entityManager; // <- This injection fails
}
From my point of view, I am specifying exactly what EntityManger should use via either #PersistenceContext(unitName) or #Qualifier
However, as the error says, springboot does not know which one of the 4 Beans use.
Am I missing something?
UPDATE
Full stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'changes': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 5: D1EntityManager,D2EntityManager,BaseEntityManager,oldDbEntityManager,deviceApiGwDbConfigurationDbEntityManager
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:356) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1383) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at com.mycompany.device.api.gw.Application.main(Application.java:35) [classes/:na]
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 5: D1EntityManager,D2EntityManager,BaseEntityManager,oldDbEntityManager,deviceApiGwDbConfigurationDbEntityManager
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1139) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1079) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:569) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:532) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:700) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:673) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:353) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
... 17 common frames omitted

Related

How to create a pool of bean in spring?

In my project , i need to call some other app SOAP url to get connection , on top of that connection obj, i need to pass various request to get response. This response i need to parse to get actual results data.
There is an API called Retrival class object when holds the connection. Need to use the same for connection i.e. pass requests and get response object.
So I can declase it as prototype scope to get these Retrival objects.
But I am using Akka Actors which fetch different data using these objects.
I cant create unknownnumber of bean of Retrival class using prototype scope. Which may later result in OOM exception.
I want to create some says 20 beans of Retrival class and use them.
How can i do it in spring, i am using spring latest version.
I tried to use commonspool2targetsource but as by Retrival class imported from other application jar... which is not recognizing Retrival.class in the class path.
Not sure how to go about it , any help is highly appreciated.
Here is the piece of sample code what i am doing:
#Bean(name="retriver")
#Scope("prototype")
public Retriver retriver() {
Retriver dr = null;
try {
dr = new Retriver(config.getUserName(),
config.getPassword(),
config.getUrl());
} catch (Exception e) {
logger.error("Exepction in creating SOAP datasource connection");
}
return dr;
}
#Bean
public CommonsPool2TargetSource RetriverPooledTargetSource() {
final CommonsPool2TargetSource commonsPoolTargetSource = new CommonsPool2TargetSource();
commonsPoolTargetSource.setTargetBeanName("Retriver");
commonsPoolTargetSource.setTargetClass(Retriver.class); //Getting error here....
commonsPoolTargetSource.setMaxSize(10);
return commonsPoolTargetSource;
}
#Bean
public ProxyFactoryBean proxyFactoryBean() {
ProxyFactoryBean p = new ProxyFactoryBean();
p.setTargetSource(RetriverPooledTargetSource());
return p;
}
Error : The type org.apache.commons.pool2.PooledObjectFactory cannot be resolved. It is indirectly referenced from required .class files
Part-2 Question:
Changing to below common-pool2 ..earlier error disappeared.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
But when I say pool.getActive as below is displaying count as 0
CommonsPool2TargetSource pool = configurationUtils.retrieverPooledTargetSource();
System.out.println( " pool.getActiveCount " + pool.getActiveCount());
There is no exception as such but when i checked the pool object above.
There is a filed called creationException
Which reads as below :
java.lang.Exception
at org.apache.commons.pool2.impl.BaseGenericObjectPool.<init>(BaseGenericObjectPool.java:147)
at org.apache.commons.pool2.impl.GenericObjectPool.<init>(GenericObjectPool.java:105)
at org.springframework.aop.target.CommonsPool2TargetSource.createObjectPool(CommonsPool2TargetSource.java:225)
at org.springframework.aop.target.CommonsPool2TargetSource.createPool(CommonsPool2TargetSource.java:205)
at org.springframework.aop.target.AbstractPoolingTargetSource.setBeanFactory(AbstractPoolingTargetSource.java:83)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1767)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1732)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.resolveBeanReference(ConfigurationClassEnhancer.java:394)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:366)
at com.spgmi.ca.prescore.config.ConfigurationUtils$$EnhancerBySpringCGLIB$$f3eea85f.dataRetrieverPooledTargetSource(<generated>)
at com.spgmi.ca.prescore.config.ConfigurationUtils.proxyFactoryBean(ConfigurationUtils.java:60)
at com.spgmi.ca.prescore.config.ConfigurationUtils$$EnhancerBySpringCGLIB$$f3eea85f.CGLIB$proxyFactoryBean$2(<generated>)
at com.spgmi.ca.prescore.config.ConfigurationUtils$$EnhancerBySpringCGLIB$$f3eea85f$$FastClassBySpringCGLIB$$861ac14b.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at com.spgmi.ca.prescore.config.ConfigurationUtils$$EnhancerBySpringCGLIB$$f3eea85f.proxyFactoryBean(<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)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:620)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getSingletonFactoryBeanForTypeCheck(AbstractAutowireCapableBeanFactory.java:974)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryBean(AbstractAutowireCapableBeanFactory.java:848)
at org.springframework.beans.factory.support.AbstractBeanFactory.isTypeMatch(AbstractBeanFactory.java:565)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:514)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:485)
at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:227)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1403)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at com.spgmi.ca.prescore.PreScoreProducerApplication.main(PreScoreProducerApplication.java:34)
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.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Question 3
When call this
CommonsPool2TargetSource pool = configurationUtils.dataRetrieverPooledTargetSource();
dataRetriever = (DataRetriever) pool.getTarget();
System.out.println(" " + dataRetriever);
It throws below exception: What am i doing wrong here ?
Caused by: java.lang.IllegalStateException: No Commons ObjectPool available
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.aop.target.CommonsPool2TargetSource.getTarget(CommonsPool2TargetSource.java:234)
at com.spgmi.ca.prescore.actor.CompanyTransIndustryActor.preStart(CompanyTransIndustryActor.java:63)
at akka.actor.Actor$class.aroundPreStart(Actor.scala:510)
at akka.actor.UntypedActor.aroundPreStart(UntypedActor.scala:95)
at akka.actor.ActorCell.create(ActorCell.scala:590)
... 9 more
You need to add the following dependency (this is for maven build):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>

Create several bean with constructer

I am trying to create several beans with constructer but it keeps failing.
ServerStater.java
#SpringBootApplication
public class ServerStarter {
public static void main(String[] args)
{
ConfigurableApplicationContext context = SpringApplication.run(ServerStarter.class, args);
NettyTcpServer server1 = context.getBean(NettyTcpServer.class, (Integer) 10001);
server1.start();
NettyTcpServer server2 = context.getBean(NettyTcpServer.class, (Integer) 10002);
server2.start();
}
}
NettyTcpServer
#Component
public class NettyTcpServer {
private int port;
#Autowired
public NettyTcpServer(int port)
{
this.port = port;
}
...
}
So, basically, I want to make two beans which have different variable values with the same class. I made Constructer which will get a port to open TCP socket, and I passed the int parameter when creating the beans when the program is started. Do I miss understood how to use these annotations? I atteched error message when running.
APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in com.telcuon.korail.netty.NettyTcpServer
required a bean of type 'int' that could not be found.
Action:
Consider defining a bean of type 'int' in your configuration.
[WARNING] java.lang.reflect.InvocationTargetException 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.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:558)
at java.lang.Thread.run(Thread.java:748) Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'nettyTcpServer' defined in file
[C:\Java\TCO-AppCard-Korail-Branch-Server\target\classes\com\telcuon\korail\netty\NettyTcpServer.class]: Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'int' available: expected at least 1 bean
which qualifies as autowire candidate. Dependency annotations: {} at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:767)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1308)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1154)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at com.telcuon.korail.ServerStarter.main(ServerStarter.java:22) ...
6 more Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'int' available: expected at least 1 bean
which qualifies as autowire candidate. Dependency annotations: {} at
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1646)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1205)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:855)
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:758)
... 24 more

No qualifying bean of type Repository

I am using spring boot application for my project.
I have defined commons module which has repositories required for my project.
My main module which is dependent on commons is running fine with this dependency.
However,when I run following test class which is annotated with #SpringBootTest,it gives exception
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ApigatewayApplication.class)
#TestPropertySource(locations = "classpath:application-integrationtest.properties")
public class APIApplicationTests {
#Autowired
private MockMvc mvc;
#Test
public void contextLoads() throws Exception {
MvcResult mvcResult = mvc.perform(get("/public/login")
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println(mvcResult.toString());
}
}
When I run this testcase it gives following exception
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xxxService': Unsatisfied dependency expressed through field 'xxxRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxx.xxxx.commons.repository.IXXXRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:578)
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.AbstractBeanFactory$$Lambda$120/1201454821.getObject(Unknown Source)
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.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.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:138)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xx.xxx.commons.repository.IXXXRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 45 more
I tried to solve this problem my using #EnableJpaRepositories(basePackages = "com.xxx.xxx"). But this will give following problem
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 28 more
Anyone facing this problem?
You can autowire MockMvc, but you need to add the following
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
#AutoConfigureMockMvc
To your test class, so it autoconfigures MockMvc, let me know if it works

Getting a SessionFactory in Spring Boot 2.0 / Hibernate 5

I was using HibernateJpaSessionFactoryBean in Spring Boot 1.5.x to get a session factory bean for my sessions. Since that's deprecated now, I'm trying to use the session factory by unwrapping in an EntityManagerFactory. But, I can't get EntityManagerFactory to be autowired. There's no bean defining it.
What do I need to do to wire in an EntityManagerFactory? entityManagerFactory remains null.
/**
* A class to hold necessary data access beans.
*/
#Configuration
#EnableTransactionManagement
public class DataBeans {
#Autowired
private EntityManagerFactory entityManagerFactory;
/**
* This bean needs to be wired in so that a SessionFactory can be wired in to other data access beans.
*
* #return a session factory bean
*/
#Bean
public SessionFactory sessionFactoryProvider() {
return entityManagerFactory.unwrap(SessionFactory.class);
}
}
#SpringBootApplication
public class AppBootMain {
public static void main(String[] args) {
SpringApplication.run(AppBootMain.class, args);
}
}
application.properties:
spring.datasource.driverClassName=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:student_db
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.HSQLDialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create-drop
# this ensures that a session factory bean is available
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
Note: i tried changing the current_session_context_class to specify hibernate5 in the package, but no success.
error running bootRun:
```
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataBeans': Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactoryProvider' defined in class path resource [org/webapp/example/school/data/repository/DataBeans.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'dataBeans' - consider declaring the factory method as static for independence from its containing instance. Factory method 'sessionFactoryProvider' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1348)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:578)
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.AbstractBeanFactory$$Lambda$94/681094281.getObject(Unknown Source)
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.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 org.webapp.example.school.AppBootMain.main(AppBootMain.java:27)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactoryProvider' defined in class path resource [org/webapp/example/school/data/repository/DataBeans.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'dataBeans' - consider declaring the factory method as static for independence from its containing instance. Factory method 'sessionFactoryProvider' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1254)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1103)
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.AbstractBeanFactory$$Lambda$94/681094281.getObject(Unknown Source)
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.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 20 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'dataBeans' - consider declaring the factory method as static for independence from its containing instance. Factory method 'sessionFactoryProvider' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
... 33 common frames omitted
Caused by: java.lang.NullPointerException: null
at org.webapp.example.school.data.repository.DataBeans.sessionFactoryProvider(DataBeans.java:30)
at org.webapp.example.school.data.repository.DataBeans$$EnhancerBySpringCGLIB$$ebde0844.CGLIB$sessionFactoryProvider$0(<generated>)
at org.webapp.example.school.data.repository.DataBeans$$EnhancerBySpringCGLIB$$ebde0844$$FastClassBySpringCGLIB$$f2417c25.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.webapp.example.school.data.repository.DataBeans$$EnhancerBySpringCGLIB$$ebde0844.sessionFactoryProvider(<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:483)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 34 common frames omitted
> Task :bootRun FAILED
I tried putting EntityManagerFactory as a paraemter to the bean method that creatrs teh session factory, but it failed due to circular dependency.
#Bean
public SessionFactory sessionFactoryProvider(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.unwrap(SessionFactory.class);
}
I encountered the same problem when upgrade from 1.5 to 2.1.3 and resolved by getting the Session / SessionFactory in the Dao class instead of autowire when spring init.
Following is an example:
Remove the DataBeans in you example
In the Dao classes use following to get the Session:
#Repository
#Transactional
public class XXXDao {
#Autowired
private EntityManager entityManager;
private Session getSession() {
return entityManager.unwrap(Session.class);
}
...
}
If you really need the SessionFactory, use following coding and beware that the you might need to handle the transaction manually.
#Repository
public class XXXDao {
#Autowired
private EntityManagerFactory entityManagerFactory;
private SessionFactory getSessionFactory() {
return entityManagerFactory.unwrap(SessionFactory.class);
}
...
}
I would suggest you check also the
Spring boot hibernate no transaction is in progress for the transaction issue
I did the same as you but without #EnableTransactionManagement.
Here my class and properties.
#Configuration
public class SessionFactoryConfiguration {
#Autowired
private EntityManagerFactory entityManagerFactory;
#Bean
public SessionFactory getSessionFactory() {
return entityManagerFactory.unwrap(SessionFactory.class);
}
}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=false
spring.jpa.properties.hibernate.jdbc.batch_size=10
spring.jpa.properties.hibernate.id.new_generator_mappings=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
Adding #EnableTransactionManagement means Transaction will be enabled but you have to configure it via PlatformTransactionManager. Spring autoconfiguration will do it so you don't have to declare it.

Sprint Boot Data JPA: No qualifying bean of type 'java.util.Set<javax.persistence.EntityManager>' available

I am unable to get started with spring-boot-starter-data-jpa. I've created a simple Spring Boot app following this guide, but with Hibernate and related config.
build.gradle:
dependencies {
// Spring stuff
compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.5.1.RELEASE'
compile 'org.springframework.data:spring-data-jpa'
compile 'org.springframework:spring-webmvc'
// Jackson
compile 'com.fasterxml.jackson.core:jackson-databind:+'
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:+'
// Postgres
compile 'org.postgresql:postgresql:+'
// Hibernate
compile 'org.hibernate:hibernate-core:5.2.8.Final'
}
Whenever I try to run the app, I end up with the following:
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-02-24 16:20:27.710 ERROR 1070 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jpaContext': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.Set<javax.persistence.EntityManager>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at nl.eonics.cdaas.service.Application.main(Application.java:14) [main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.Set<javax.persistence.EntityManager>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 23 common frames omitted
I have seen this bug (which is reportedly fixed as of 1.10.7) but downgrading spring-data-jpa to 1.9.x didn't help, I still got the same error.
Any ideas?
The problem is in hibernate-core. Removing it from dependencies resolves the issue.
I had the same problem when using Spring Boot 2.0.3-RELEASE with Hibernate/JPA with PostgreSQL 10.
I had the following configuration for JPA:
#EnableJpaRepositories
public class DomainConfiguration {
#Value("${database.password}")
private String password;
#Value("${database.url}")
private String url;
#Value("${database.username}")
private String userName;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Driver.class.getCanonicalName());
dataSource.setUrl(this.url);
dataSource.setUsername(this.userName);
dataSource.setPassword(this.password);
return dataSource;
}
#Bean
#DependsOn("flyway")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setJpaDialect(new HibernateJpaDialect());
factory.setPersistenceUnitName("MTH");
factory.setPackagesToScan("nl.mth.sync.domain");
factory.setDataSource(dataSource());
return factory;
}
#Bean
public Flyway flyway(DataSource dataSource) {
log.debug("--- configurating flyway ---");
Flyway fly = new Flyway();
fly.setDataSource(dataSource);
fly.migrate();
return fly;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
And I fixed the issue by adding the following method:
#Bean
public EntityManager entityManager(LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean) {
return localContainerEntityManagerFactoryBean.getObject().createEntityManager();
}
It can be solved by adding as argument to the notation the following:
#SpringBootApplication
This would be in the main method:
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class})

Categories

Resources