Search code examples
javaspringconnection-poolingpool

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


Solution

  • You need to add the following dependency (this is for maven build):

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>          
        </dependency>