Amir Pashazadeh
Amir Pashazadeh

Reputation: 7322

Loading Properties from Database using Java Config with Spring Boot

I created a FactoryBean<Properties> as

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.

Now I want to use the same thing in Spring Boot and 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.

Is there any way to create the datasource before PRopertySourcesPlaceHolderConfigurer?

Upvotes: 2

Views: 4293

Answers (2)

sujithramanathan
sujithramanathan

Reputation: 1249

I have the similar type of requirement where the properties should get loaded from database and binded to the respective spring beans.

I written the example in the below github repository.

Load Properties from DB

Upvotes: 0

yvoytovych
yvoytovych

Reputation: 871

Basically you need to take the dependency as a @Bean method parameter this way:

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

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

Upvotes: 0

Related Questions