弹簧启动无法读取Yaml属性

问题描述 投票:0回答:2

我写了一个Spring批处理应用程序,在src / main / resources文件夹中配置了数据库连接属性。

作业配置如下:

@Import({DataSourceConfiguration.class})
@Configuration
public class JobConfiguration {
    @Autowired
    private DataSourceConfiguration dataSourceConfig;
    ......
}

DataSourceConfiguration类如下:

@Configuration
@EnableConfigurationProperties(DatabaseConfiguration.class)
public class DataSourceConfiguration {

    @Autowired
    private DatabaseConfiguration dbConfiguration;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(dbConfiguration.getDriver());
        dataSource.setUrl(dbConfiguration.getUrl());
        dataSource.setUsername(dbConfiguration.getUser());
        dataSource.setPassword(dbConfiguration.getPassword());

        return dataSource;
    }
}

DatabaseConfiguration类如下:

@ConfigurationProperties("jdbc")
public class DatabaseConfiguration {
    private String driver;
    private String url;
    private String user;
    private String password;

    //getter/setter methods
    ......
}

application.yml文件如下:

jdbc:
    driver: oracle.jdbc.OracleDriver
    url: 'jdbc:oracle:thin:@hostname'
    user: username
    password: password

当我运行spring批处理时,异常显示不从yml文件中读取属性。我已经按照上述配置的文档,我不知道缺少什么。请详细说明。谢谢。

Caused by: java.lang.IllegalArgumentException: Property 'driverClassName' 
must not be empty
at org.springframework.util.Assert.hasText(Assert.java:276)
at org.springframework.jdbc.datasource.DriverManagerDataSource.setDriverClassName(DriverManagerDataSource.java:124)
at com.telus.workforcemgmt.batchcloud.configuration.DataSourceConfiguration.dataSource(DataSourceConfiguration.java:28)
at com.telus.workforcemgmt.batchcloud.configuration.DataSourceConfiguration$$EnhancerBySpringCGLIB$$7e128c57.CGLIB$dataSource$4(<generated>)
at com.telus.workforcemgmt.batchcloud.configuration.DataSourceConfiguration$$EnhancerBySpringCGLIB$$7e128c57$$FastClassBySpringCGLIB$$b7fd119a.invoke(<generated>)
configuration yaml spring-batch
2个回答
0
投票

在DatabaseConfiguration.java中检查“driver”属性的setter方法名称

是吗?

public void setDriver(String driver) {
        this.driver = driver;
    }

0
投票

最后,我能够通过环境api检索属性,不知道为什么配置属性绑定不起作用。修改后的版本粘贴如下:

@Configuration
@PropertySource("classpath:application.yml")
public class DataSourceConfiguration {

@Autowired
Environment env;

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();

    dataSource.setDriverClassName(env.getProperty("jdbc.driver"));
    dataSource.setUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.user"));
    dataSource.setPassword(env.getProperty("jdbc.password"));

    return dataSource;
}
© www.soinside.com 2019 - 2024. All rights reserved.