我应该在哪里初始化我的Apache commons pool2,以便可以从其他类访问它

时间:2018-05-01 15:35:30

标签: java rest jax-rs apache-commons-pool

我正在开发基于jax-rs的REST服务。我需要为我的应用程序连接池,所以我将使用commons pool2。我计划在实现ServletContextListener的类中初始化我的池,以便在应用程序启动时初始化池。问题是我无法弄清楚如何从我的FolderService类中访问我的池。

我试图在下面添加适当的代码。谢谢!

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 ;
    }

}

0 个答案:

没有答案