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>
Related
I'm trying to read a configuration file from command line. In main I do this:
public static void main(String[] args) {
if(args.length > 0) {
SpringApplication.run(HeliosAdminBackendApplication.class, args);
} else {
System.out.println("Error");
System.exit(0);
}
}
And, following this question, I've created a class MyConfig like this:
import lombok.Getter;
#Configuration
#ConfigurationProperties
#PropertySource(value = "file:${ConfigPath}")
public class MyConfig {
#Getter
#Value("${property_name}")
private String myproperty;
}
Then I've created the .jar file, then went in the folder containing the jar and try to run it by doing:
java -jar myapp.jar --spring.config.location=file:application.yml
My application.yml file is the same folder of my jar. I've also set the path to C:/my/path/to/folder/ but the error persists. Is the path written wrong? Or do I have to add/modify something in the code?
EDIT
Full stack trace:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed
to parse configuration class
[it.sysdata.helios_backend_admin.HeliosAdminBackendApplication];
nested exception is java.lang.IllegalArgumentException: Could not
resolve placeholder 'ConfigPath' in value "file:${ConfigPath}"
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:181)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:315)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:232)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:691)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:528)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
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 it.sysdata.helios_backend_admin.HeliosAdminBackendApplication.main(HeliosAdminBackendApplication.java:24)
... 8 more Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'ConfigPath' in value
"file:${ConfigPath}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:172)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:237)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:211)
at org.springframework.core.env.AbstractEnvironment.resolveRequiredPlaceholders(AbstractEnvironment.java:575)
at org.springframework.context.annotation.ConfigurationClassParser.processPropertySource(ConfigurationClassParser.java:450)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:271)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:191)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:295)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:199)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167)
... 21 more
Here is the answer for your question regarding Why do I have to use "additional" and not just location?
First of all when ever you use spring.config.location for loading configuration properties then spring-boot trys to search the configuration at classpath or under config directory. Here is the order of search -
file:./config/
file:./
classpath:/config/
classpath:/
But remember if you are using the spring.config.locaton then it will always look for either "classpath" or "config" not the external configuration.
To load the external configuration/custom configuration then spring boot provides "spring.config.additional-location" which search the configuration in following order -
file:./custom-config/
classpath:custom-config/ (This is was your case)
file:./config/
file:./
classpath:/config/
classpath:/
I hope now got the answer why to use the "spring.config.additional-location" for loading external configuration.
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
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
I'm getting an error creating a HighEndRestClient bean in a SpringBoot app. I have done a test 'app' where I checked I can instantiate the objects I want and then make the calls I want to and I am now making baby steps into making a new application.
I have these dependencies in the pom
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>5.6.3</version>
</dependency>
and I have written this very basic code in a configuration class which doesn't do much yet
#Configuration
#PropertySource(value = "classpath:application.properties")
#EnableElasticsearchRepositories(basePackages = "com.indexbuilder.es.repo")
public class ElasticsearchConfiguration {
#Value("${elasticsearch.host}")
private String EsHost;
#Value("${elasticsearch.port}")
private int EsPort;
#Value("${elasticsearch.clustername}")
private String EsClusterName;
#Bean
public RestClientBuilder coreBuilder() throws Exception {
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
builder.setMaxRetryTimeoutMillis(10000);
builder.setFailureListener(new RestClient.FailureListener() {
#Override
public void onFailure(HttpHost host) {
System.out.println("FAILURE !!!! FailureListener HAS WOKEN UP!!!! CREATYE A FAILURE LISTENER BEAN" );
}
});
return builder;
}
#Bean
public RestClient restLowLevelClient() throws Exception{
RestClient restClient = coreBuilder().build();
return restClient;
}
This works fine as far as I can see (I haven't done much with it yet...)
when I add this (initially I was passing in the RestClient bean but now I'm temporarily creating a local object for more clarity)
#Bean
public RestHighLevelClient restHighLevelClient() throws Exception{
RestClient restClient = coreBuilder().build();
RestHighLevelClient client = new RestHighLevelClient(restClient);
return client;
}
I get this java.lang.NoClassDefFoundError error
=========|_|==============|___/=///_/ :: Spring Boot :: (v1.5.1.RELEASE)
[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:527)
at java.lang.Thread.run(Thread.java:745) Caused by:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'restHighLevelClient' defined in class path
resource
[com/indexbuilder/configuration/ElasticsearchConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.elasticsearch.client.RestHighLevelClient]: Factory
method 'restHighLevelClient' threw exception; nested exception is
java.lang.NoClassDefFoundError:
org/elasticsearch/action/main/MainRequest at
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:598)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1140)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1034)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:525)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:744)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
at
com.indexbuilder.SpringBootStartUpConfig.main(SpringBootStartUpConfig.java:84)
... 6 more Caused by:
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.elasticsearch.client.RestHighLevelClient]: Factory
method 'restHighLevelClient' threw exception; nested exception is
java.lang.NoClassDefFoundError:
org/elasticsearch/action/main/MainRequest at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
... 24 more Caused by: java.lang.NoClassDefFoundError:
org/elasticsearch/action/main/MainRequest at
com.indexbuilder.configuration.ElasticsearchConfiguration.restHighLevelClient(ElasticsearchConfiguration.java:95)
at
com.indexbuilder.configuration.ElasticsearchConfiguration$$EnhancerBySpringCGLIB$$62f74d9a.CGLIB$restHighLevelClient$1()
at
com.indexbuilder.configuration.ElasticsearchConfiguration$$EnhancerBySpringCGLIB$$62f74d9a$$FastClassBySpringCGLIB$$2b29ad7b.invoke()
at
org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at
org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
at
com.indexbuilder.configuration.ElasticsearchConfiguration$$EnhancerBySpringCGLIB$$62f74d9a.restHighLevelClient()
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:162)
... 25 more Caused by: java.lang.ClassNotFoundException:
org.elasticsearch.action.main.MainRequest at
java.net.URLClassLoader.findClass(URLClassLoader.java:381) at
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at
java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 36 more
Can anyone point me in the right direction ?
You probably need the core dependency as well:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.3</version>
</dependency>
A NoClassDefFoundError is generally a configuration error - it means that the code you use references a certain class, but the class itself isn't in the classpath. In this case, this might also be a dependency management error in the relevant Elasticsearch poms themselves, as they should include the needed classes - but there's not much you can do about that other than perhaps file an issue.
I had the same problem.
ElasticSearch pointed to old version:
org.elasticsearch:elasticsearch:6.2.3 -> 1.5.2
I used dependencyManagement gradle plugin to force use the version I mention:
dependencyManagement {
dependencies {
dependency 'org.elasticsearch:elasticsearch:6.2.3'
}}
For more info: https://github.com/spring-gradle-plugins/dependency-management-plugin
I want to add a connection pool to my existing web application, which has been made using Spring Boot 1.5.1.
The datasource configuration is made in application.properties as follows:
spring.datasource.url=jdbc:jtds:sqlserver://localhost:1433;databaseName=MyDatabase;instance=SQLServer2014;
spring.datasource.username=myuser
spring.datasource.password=passwd
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
I don't need to make any further configuration, with this is enough.
It isn't clear enough in the official docs, although parameters are shown, nor in the Spring Boot docs.
So, I've been looking for solutions over there (this one, this one too...).
I've made several trials, but everytime I run the app, exceptions regarding HikariCP are thrown.
When adding spring.datasource.type=com.zaxxer.hikari.HikariDataSource, the following exception is thrown:
2017-02-15 12:12:23.955 WARN 14844 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
2017-02-15 12:12:23.964 INFO 14844 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-02-15 12:12:23.970 ERROR 14844 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[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.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[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.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.1.RELEASE.jar:1.5.1.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 com.ingartek.ws.pps.PrestacionesPoliticasSocialesInternoApplication.main(PrestacionesPoliticasSocialesInternoApplication.java:26) [classes/:na]
Caused by: java.lang.AbstractMethodError: null
at net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833) ~[jtds-1.3.1.jar:1.3.1]
at com.zaxxer.hikari.pool.PoolBase.checkDriverSupport(PoolBase.java:422) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.PoolBase.setupConnection(PoolBase.java:393) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:351) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:196) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:442) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:505) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:113) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:97) ~[HikariCP-2.6.0.jar:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 16 common frames omitted
So, which is the simplest way to add hikaricp to my application.properties?
You are getting below error.
Caused by: java.lang.AbstractMethodError: null at net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)
Issue is that net.sourceforge.jtds.jdbc.JtdsConnection doesn't implement isValid so you need to specify a connection-test-query to ensure that isValid method isn't called. Try by adding below property in your application.properties file.
spring.datasource.hikari.connection-test-query=SELECT 1
For using multiple datasources (Spring Boot 2.0), I had to do the following to get this to work (setting spring.datasource.hikari.connection-test-query property only worked when using a single datasource):
#Configuration
public class DataConfig {
#Bean
#Primary
#ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
HikariDataSource ds = (HikariDataSource) DataSourceBuilder.create().build();
ds.setConnectionTestQuery("SELECT 1");
return ds;
}
#Bean(name="secondDataSource")
#ConfigurationProperties(prefix="spring.datasource.second")
public DataSource secondDataSource() {
HikariDataSource ds = (HikariDataSource) DataSourceBuilder.create().build();
ds.setConnectionTestQuery("SELECT 1");
return ds;
}
#Bean(name="primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(DataSource primaryDataSource) {
return new JdbcTemplate(primaryDataSource);
}
#Bean(name="secondJdbcTemplate")
public JdbcTemplate secondJdbcTemplate(#Qualifier("secondDataSource") DataSource secondDataSource) {
return new JdbcTemplate(secondDataSource);
}
}
I ran into the same problem and found the solution from this discussion.
It looks like, before doing any further configurations Hikari CP tests the validity of the connection by executing a test query which is missing in this case.
So as suggested by the earlier answer, you should add one test query in your application.properties file.
If you are using Oracle or mySql then you can use the following query instead (as SELECT 1 doesn't work here):
spring.datasource.hikari.connection-test-query=SELECT 1 FROM DUAL
Note: DUAL is a special one-row and one-column table present in Oracle and other databases. Thus it can be readily used to execute a simple test-query.