首页 > 解决方案 > 是否可以区分我在springboot中加载的数据库类型?(甲骨文与 Azure SQL)

问题描述

我试图找出如何判断我是从 bean 初始化加载 Oracle 还是 Azure SQL。目前,我必须决定在我的 helm 图表中加载哪个数据库,Oracle 或 Azure SQL。然后,我需要知道要加载哪个 xml 文件,因为查询语法略有不同。我想知道是否有办法在不使用硬编码值的情况下做到这一点。这是我的数据库 bean 配置文件:

@Configuration
@EnableConfigurationProperties
public class ProjectDataSourceConfig {

    public static final String DB_TX_MANAGER = "";

    @Bean
    @Primary
    @ConfigurationProperties("datasource.project")
    public DataSourceProperties projectDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DataSource projectDataSource() {
        return projectDataSourceProperties().initializeDataSourceBuilder().type(ComboPooledDataSource.class).build();
    }

   
    @Bean
    public NamedParameterJdbcTemplate projectJdbcTemplate() {
        return new NamedParameterJdbcTemplate(projectDataSource());
    }

    @Bean(name = DB_TX_MANAGER)
    public DataSourceTransactionManager projectDbtransactionManager() {
        return new DataSourceTransactionManager(projectDataSource());
    }
}

如果可能的话,我还需要根据我正在加载的数据库加载不同的 xml 查询文件。例如,如果我正在加载 Oracle,我希望我的存储库使用 oracle.xml 文件。这是我当前的存储库类:(我目前正在使用 oracle)

@Configuration
@Import(ProjectDataSourceConfig.class)
@PropertySource("classpath:event-sql-oracle.xml")
public class eEventRepositoryConfig {

    @Value("${EventRepository.insertEvent}")
    private String insertEvent;

    @Bean
    public EventRepository<Event> eventRepository(final NamedParameterJdbcTemplate jdbcTemplate) {
        return new EventRepository(jdbcTemplate, insertEvent);
    }
}

标签: javaoraclespring-bootazure-sql-database

解决方案


我不知道我是否可以在创建 bean 时说出来,但我可以使用 .properties 或 helm chart 来指示 db 类型。

env:
    db.type=oracle

然后将其用作占位符,@PropertySource如下所示:

@Configuration
@Import(ProjectDataSourceConfig.class)
@PropertySource("classpath:event-sql-${db.type}.xml")
public class eEventRepositoryConfig {

我将不得不更改db.type,因为我正在更改我的配置中的服务器类型。


推荐阅读