H2数据库配置未由SpringBoot IOC读取

时间:2020-04-14 16:29:32

标签: spring-boot properties h2 hikaricp

我正在为某些POC工作,我正在为其使用h2数据库,并且在application.properties文件中具有以下详细信息:

fetch('https://example.com/login', {
    method: 'POST',
    body: JSON.stringify({
        username: Uname,
        password: Upass
    })
}).then((response) => response.text()).then((responseJson) => {
    alert(JSON.stringify(responseJson));
    console.log(JSON.stringify(responseJson));
}).catch((error) => {
    alert(JSON.stringify(error));
    console.log(error);
})

我的豆类定义如下:

#datasource
ds.pc.jdbcUrl=jdbc:h2:mem:test;MODE=oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
ds.pc.type=com.zaxxer.hikari.HikariDataSource
ds.pc.driver-class-name=org.h2.Driver
ds.pc.hikari.pool-name=pc-hikari-dbcp
ds.pc.hikari.maximum-pool-size=20
ds.pc.driver-type=thin
ds.pc.validation-query=Select 1 from dual
ds.pc.primary=true
ds.pc.username=sa
ds.pc.password=

spring.h2.console.enabled=true
spring.h2.console.path=/h2

它失败,出现以下异常:

@Configuration
public class AppConfig
{
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public ConversionServiceFactoryBean conversionServiceFactoryBean()
    {
        return new ConversionServiceFactoryBean();
    }
    @Primary
    @Bean(name = "pcJdbcTemplate")
    public NamedParameterJdbcTemplate pCJdbcTemplate()
    {
        return new NamedParameterJdbcTemplate(pCDataSource());
    }

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "ds.pc")
    public DataSource pCDataSource()
    {
        return DataSourceBuilder.create().build();
    }
}

但是当我按如下所示对数据源属性进行硬编码时,它就起作用了:

java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
    at com.zaxxer.hikari.HikariConfig.validate(HikariConfig.java:958) ~[HikariCP-3.4.2.jar:?]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:109) ~[HikariCP-3.4.2.jar:?]
    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:158) ~[spring-jdbc-5.2.4.RELEASE.jar:5.2.4.RELEASE]

尝试更改属性如下:

    @Primary
    @Bean 
    public DataSource pCDataSource() 
    {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName("org.h2.Driver");
        hikariConfig.setUsername("sa"); hikariConfig.setPassword("");
        hikariConfig.setJdbcUrl(
                "jdbc:h2:mem:test;MODE=oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
        return new HikariDataSource(hikariConfig); 
    }

仍然无法正常工作。

我的application.properties文件有什么问题,原因是未被​​读取?

我也无法在localhost:8080 / h2看到h2控制台

1 个答案:

答案 0 :(得分:0)

问题是我的application.properties文件位于src / main / resources下名为 appConfig 的文件夹下。

解决方案1: appConfig 重命名为 config

转到第2.3节。位于documentation的应用程序属性文件。它说明了config文件夹为何起作用。

解决方案2:将属性文件直接移到src / main / resources下

愚蠢的我。花了好几个小时才发现事情很简单。