簡體   English   中英

使用Java Config和Spring Boot從數據庫加載屬性

[英]Loading Properties from Database using Java Config with Spring Boot

我創建了一個FactoryBean<Properties>作為

public final class SystemProperteisFactoryBean implements FactoryBean<Properties> {

    private static final String QUERY = "select * from tb_system_properties";

    private final NamedParameterJdbcTemplate jdbcTemplate;

    public SystemProperteisFactoryBean (DataSource datasource) {
        this.jdbcTemplate = new NamedParameterJdbcTemplate (datasource);
    }

    @Override
    public Properties getObject() {
        Properties result = new Properties();
        jdbcTemplate.query(QUERY,
            (ResultSet rs) -> result.setProperty(rs.getString(1), rs.getString(2));
        return result;
    }

    @Override
    public Class<?> getObjectType() {
        return Properties.class;
    }

    @Override
    public boolean isSingletone() {
        return true;
    }
}

此類在使用帶有XML配置的Spring時可以很好地工作,我使用JNDI名稱獲得DataSource,然后創建適當的屬性,然后通過XML標記使用propertiesPlaceHoldeConfigurer。

現在,我想在Spring Boot和Java Config中使用相同的功能。

當我將ProprtySourcesPlaceHolderConfigurer定義為bean時(在@Configuration類的靜態方法中),Spring嘗試在數據源之前創建此bean。

有什么方法可以在PRopertySourcesPlaceHolderConfigurer之前創建數據源?

基本上,您需要通過以下方式將依賴項作為@Bean方法參數:

@Configuration
public static class AppConfig {
    @Bean
    public SystemPropertiesFactoryBean systemProperties(DataSource dataSource) {
      return new SystemPropertiesFactoryBean(dataSource);
    }

    @Bean
    public DataSource dataSource() {
      //  return new data source
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM