懒惰地创建DataSource和事务管理器

时间:2017-11-24 07:36:06

标签: java spring

我有一个数据库访问模块,可以与多种类型的数据源进行交互。

某些更高级的模块使用数据库模块而不与JDBC数据源交互。因此,我希望将数据源定义为惰性。但是,我还定义了一个事务管理器,我无法将其定义为惰性,因为它不是我代码中的直接依赖项。由于事务管理器依赖于数据源,因此始终会创建后者。

@Configuration
@EnableTransactionManagement
public class SpringConfig {

    @Bean(destroyMethod = "close")
    @Lazy
    @Autowired
    public DataSource dataSource() throws Exception {
        //create data source
    }

    @Bean
    @Lazy
    @Autowired
    public PlatformTransactionManager txManager() throws Exception {
        DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource());
        return txManager;
    }
}

@Lazy
@Repository("FundRepository")
public class MyRepository {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
         jdbcTemplate = new JdbcTemplate(dataSource);
    }
}

知道如何使这项工作吗?

0 个答案:

没有答案
相关问题