Spring has a useful bean (LazyConnectionDataSourceProxy) that defers using a database connection until it is actually needed. This is useful when you have a scenario whereby all the data required might hit a cache:
 
        @Transactional
        public void doSomething(){
           .. do some selects that might hit the cache and thus not require DB
        }
        
In this case, by the time you've entered the method, the @Transactional has already opened a new transaction and will commit uselessly at the end of it. To configure BoneCP for use with the LazyConnectionDataSourceProxy, follow the recipe below. You may want to read this blog post for a more detailed discussion.

You may also wish to refer to this other post for a commentary on switching datasources dynamically at runtime using BoneCP's DynamicDataSourceProxy.

 
         
         
         
            <!-- Hibernate SessionFactory -->
            <bean id="sessionFactory" class="..." autowire="autodetect">
            <!-- Tell hibernate to use our given datasource -->
                <property name="dataSource" ref="dataSource" /> 
            
                <property name="hibernateProperties">
                    <props>
                        <prop key="hibernate.dialect">...</prop>
                        ...
                    </props>
                </property>
            </bean>
            
            <!-- Spring bean configuration. Tell Spring to bounce off BoneCP -->
            <bean id="dataSource"
                class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
                <property name="targetDataSource">
                    <ref local="mainDataSource" />
                </property>
            </bean>
            
            <!-- BoneCP configuration -->
            <bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
                <property name="driverClass" value="com.mysql.jdbc.Driver" />
                <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1/yourdb" />
                <property name="username" value="root"/>
                <property name="password" value="abcdefgh"/>
                <property name="idleConnectionTestPeriod" value="60"/>
                <property name="idleMaxAge" value="240"/>      
                <property name="maxConnectionsPerPartition" value="60"/>
                <property name="minConnectionsPerPartition" value="20"/>
                <property name="partitionCount" value="3"/>
                <property name="acquireIncrement" value="10"/>                              
                <property name="statementsCacheSize" value="50"/>
                <property name="releaseHelperThreads" value="3"/>
            </bean>