Мне нужно динамически создать источник данных, jdbcTemplate и TransactionTemplate.
Должен ли я как-то закрыть источник данных, jdbcTeplate< /code> и TransactionTemplate самостоятельно, так как я их создаю сам?
Рассматриваю два варианта создания:
Мне нужно динамически создать источник данных, jdbcTemplate и TransactionTemplate. Должен ли я как-то закрыть источник данных, jdbcTeplate< /code> и TransactionTemplate самостоятельно, так как я их создаю сам? Рассматриваю два варианта создания: [list][*]Первый вариант [code]@Configuration @EnableTransactionManagement public class DatasourceConfiguration {
@Bean @ConfigurationProperties(prefix = "spring.datasources") public Map dataSourceProperties() { return new HashMap(); }
@Bean public Map dataSources(Map dataSourceProperties) { Map dataSources = new HashMap(); dataSourceProperties.forEach((name, properties) -> { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl(properties.getUrl()); dataSource.setUsername(properties.getUsername()); dataSource.setPassword(properties.getPassword()); dataSource.setDriverClassName(properties.getDriverClassName()); dataSources.put(name, dataSource); }); return dataSources; }
@Bean public Map transactionTemplates(Map dataSources) { Map transactionTemplates = new HashMap(); dataSources.forEach((name, dataSource) -> { DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); transactionTemplates.put(name, new TransactionTemplate(transactionManager)); }); return transactionTemplates; }
@Bean public Map jdbcTemplates(Map dataSources) { Map jdbcTemplates = new HashMap(); dataSources.forEach((name, dataSource) -> { jdbcTemplates.put(name, new JdbcTemplate(dataSource)); }); return jdbcTemplates; }
} [/code]
[*]Второй вариант [code]@Configuration @EnableTransactionManagement public class DatasourceConfiguration {
@Bean @ConfigurationProperties(prefix = "spring.datasources") public Map dataSourceProperties() { return new HashMap(); }
@Bean public Map dataSources(Map dataSourceProperties) { Map dataSources = new HashMap(); dataSourceProperties.forEach((name, properties) -> { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl(properties.getUrl()); dataSource.setUsername(properties.getUsername()); dataSource.setPassword(properties.getPassword()); dataSource.setDriverClassName(properties.getDriverClassName()); dataSources.put(name, dataSource); }); return dataSources; }
@Bean public Map dbManagers(Map dataSources) { Map dbManagers = new HashMap(); dataSources.forEach((name, dataSource) -> { DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); dbManagers.put(name, new DBManager(dataSource, new JdbcTemplate(dataSource), new TransactionTemplate(transactionManager)));