DbcpDataSourceProvider implements Provider<DataSource> { public DataSource get() { log.debug("Configuring DataSource wrapped in a Database Connection Pool, using custom loader"); Path jdbcDriverClassPath = settings.getPath(PersistenceConf.DRIVER_PATH, homeFolder); log.debug("Loading JDBC Driver with custom class path: " + jdbcDriverClassPath); ClassLoader classLoader = ClassLoaderUtils.initiate(jdbcDriverClassPath); String className = settings.getString(PersistenceConf.DRIVER_CLASS); String connectURI = settings.getString(PersistenceConf.JDBC_CONNECTION_URI); Driver driver = getJdbcDriver(classLoader, className); Properties properties = new Properties(); properties.put("user", settings.getString(PersistenceConf.JDBC_USERNAME)); properties.put("password", settings.getString(PersistenceConf.JDBC_PASSWORD)); ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectURI, properties); ObjectName dataSourceJmxName; try { dataSourceJmxName = new ObjectName("no.difi.oxalis", "connectionPool", "OxalisDB"); } catch (MalformedObjectNameException e) { throw new IllegalStateException(e.getMessage(), e); } PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory, dataSourceJmxName); String validationQuery = settings.getString(PersistenceConf.DBCP_VALIDATION_QUERY); if (validationQuery != null) { poolableConnectionFactory.setValidationQuery(validationQuery); } GenericObjectPool<PoolableConnection> genericObjectPool = new GenericObjectPool<>(poolableConnectionFactory); poolableConnectionFactory.setPool(genericObjectPool); genericObjectPool.setMaxTotal(settings.getInt(PersistenceConf.DBCP_MAX_TOTAL)); genericObjectPool.setMaxIdle(settings.getInt(PersistenceConf.DBCP_MAX_IDLE)); genericObjectPool.setMaxWaitMillis(10000); genericObjectPool.setTestOnBorrow(true); genericObjectPool.setTestWhileIdle(true); genericObjectPool.setTimeBetweenEvictionRunsMillis(60 * 60 * 1000); return new PoolingDataSource(genericObjectPool); } @Inject  DbcpDataSourceProvider(Settings<PersistenceConf> settings, @Named("home") Path homeFolder); DataSource get();  }
@Test public void oxalisDataSourceFactoryIsSingleton() throws Exception { assertNotNull(dataSourceProvider); assertEquals(dataSourceProvider, dataSourceProvider2, "Seems the Singleton pattern in DataSourceProviderFactory is not working"); DataSource dataSource1 = dataSourceProvider.get(); assertNotNull(dataSource1); DataSource dataSource2 = dataSourceProvider.get(); assertEquals(dataSource1, dataSource2, dataSourceProvider.getClass().getSimpleName() + " is not returning a singleton instance of DataSource"); }