0

I am developing a REST service based on jax-rs. I need connection pooling for my application so I will be using commons pool2. I plan on initializing my pool in a class the implements ServletContextListener so that when the application starts, the pool is initialized. The problem is I cant figure out how to now access my pool from within my FolderService class.

I have attempted to add appropriate code below. Thanks!

package rest.pool
@WebListener
public class TestPoolListener implements ServletContextListener {

private GenericObjectPool<GenericPool> connectionPool = null;

@Override
public void contextInitialized(ServletContextEvent arg0) {

    final GenericPool[] active = new GenericPool[10];

    PoolFactory poolFactory = new PoolFactory();

    connectionPool = new GenericObjectPool<GenericPool>(poolFactory,config);

    try {

        for(int i=0 ; i<5 ; i++) {
            active[i] = connectionPool.borrowObject();
        }

        for(int i=0 ; i<5 ; i++) {
           connectionPool.returnObject(active[i]);
        }


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public class MyPool extends BasePooledObjectFactory<ODServer>{
        @Override
        public ODServer create() {
            //create code here
        }

   }

package rest.resource;

import javax.ws.rs.*;

@Path("/folders")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)

public class FolderResource {

    FolderService folderService = new FolderService();

    @GET
    public List<Folder> getFolders(@Context UriInfo uriInfo) {

        return folderService.getAllFolders();

    }

}

package rest.service;

public class FolderService {

    public List<Folder> getAllFolders(String uri) {
        List<Folder> folders = new ArrayList<>();
        **//How do I get access to the connection pool from here?**
        return folders ;
    }

}
  • Initialize it elsewhere and pass to constructor of all those classes that need it: plain old dependency injection either implemented manually or via a dependency injection framework such as Spring or Guice – Oleg Sklyar May 04 '18 at 07:27
  • Any chance you can elaborate on your answer? Maybe a simple example or a external reference to an example? – SteamboatUsa Jun 08 '18 at 19:46

0 Answers0