简体   繁体   English

使用Java Config和Spring Boot从数据库加载属性

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

I created a FactoryBean<Properties> as 我创建了一个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;
    }
}

This class worked fine using Spring with XML config, I get DataSource using a JNDI name, and then created proper properties, and then used propertiesPlaceHoldeConfigurer via XML tag. 此类在使用带有XML配置的Spring时可以很好地工作,我使用JNDI名称获得DataSource,然后创建适当的属性,然后通过XML标记使用propertiesPlaceHoldeConfigurer。

Now I want to use the same thing in Spring Boot and Java Config. 现在,我想在Spring Boot和Java Config中使用相同的功能。

When I define a ProprtySourcesPlaceHolderConfigurer as a bean (in a static method in a @Configuration class) Spring tries to create this bean before the datasource. 当我将ProprtySourcesPlaceHolderConfigurer定义为bean时(在@Configuration类的静态方法中),Spring尝试在数据源之前创建此bean。

Is there any way to create the datasource before PRopertySourcesPlaceHolderConfigurer? 有什么方法可以在PRopertySourcesPlaceHolderConfigurer之前创建数据源?

Basically you need to take the dependency as a @Bean method parameter this way: 基本上,您需要通过以下方式将依赖项作为@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