datasourcebuilder不拾取configurationproperties(prefix=“…”)

1tu0hz3e  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(544)

我的应用程序.properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=${env.H2_USER}
spring.datasource.password=${env.H2_PASS}

spring.token-datasource.url=jdbc:mysql://${env.MYSQL_HOST}/${env.MYSQL_DB}
spring.token-datasource.username=${env.MYSQL_USER}
spring.token-datasource.password=${env.MYSQL_PASS}

my configuration.java代码段

@Configuration
public class DataSourceConfiguration {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource regularDataSource() {
        DataSource dataSource = DataSourceBuilder.create().build();
        return dataSource;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.token-datasource")
    public DataSource tokenDataSource() {
        DataSource dataSource = DataSourceBuilder.create().build();
        return dataSource;
    }
}

但是,如果我在每个 return dataSource; ,我看到datasource对象没有填充相应的属性值,例如jdbcurl null .

有什么帮助吗?
谢谢!

q3qa4bjr

q3qa4bjr1#

跟着https://docs.spring.io/spring-boot/docs/2.4.2/reference/html/howto.html#howto-两个数据源并精心编制了以下代码:

@Configuration
public class DataSourceConfiguration {

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

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.configuration")
    public HikariDataSource regularDataSource() {
        HikariDataSource dataSource = regularDataSourceProperties().initializeDataSourceBuilder()
                .type(HikariDataSource.class).build();
        return dataSource;
    }

    @Bean
    @ConfigurationProperties("spring.token-datasource")
    public DataSourceProperties tokenDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("spring.token-datasource.configuration")
    public DataSource tokenDataSource() {
        DataSource dataSource = tokenDataSourceProperties().initializeDataSourceBuilder().build();
        return dataSource;
    }
}

有趣的是,原来的代码片段不起作用,而它仍然是许多java教程和stackoverflow文章推荐的方法。例如,
https://www.baeldung.com/spring-data-jpa-multiple-databases
springboot配置并使用两个数据源

相关问题