When to use @Singleton in a Jersey resource

前端 未结 2 750
天命终不由人
天命终不由人 2021-02-14 11:56

I have a Jersey resource that access the database. Basically it opens a database connection in the initialization of the resource. Performs queries on the resource\'s methods.

2条回答
  •  醉梦人生
    2021-02-14 12:36

    You best option is to use a framework like Spring with Jersey which I outlined in a similar post. The only difference is that instead of injecting a service bean you would inject a pooled DataSource and this can easily be configured using c3p0.

    Example applicationContext.xml, notice the "scope" is set to prototype which is equivalent to a singleton in Spring parlance.

    
        
        
        
        
        
        
        
        
        
        
    
    

    In your MyResource.java you would simply add the following and Spring would inject it appropriately.

    private DataSource pooledDataSource;
    public void setPooledDataSource(DataSource pooledDataSource) {
        this.pooledDataSource = pooledDataSource;
    }
    

    Then you could change your ResponseGenerator to accept the DataSource and use this to query the database.

提交回复
热议问题