2

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?

Amir Pashazadeh
  • 7,170
  • 3
  • 39
  • 69

1 Answers1

0

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
    }
}
yvoytovych
  • 871
  • 4
  • 12
  • Could I use the default datasource created by Spring Boot? (the one configured in application.properties)? – Amir Pashazadeh Feb 13 '18 at 11:50
  • sure, spring will try to find bean by type `DataSource` here and construct it first, before `SystemPropertiesFactoryBean` – yvoytovych Feb 13 '18 at 11:56
  • I wanted to use Spring Boot's default DataSource (which is configurable to be JNDI based or created using a connection-pool provider). But it seems it is not possible using Java Config. Because Spring Boot tries to configure a ProprtySourcesPlaceHolderConfigurer before configuring most of the beans including the DataSource. – Amir Pashazadeh Feb 17 '18 at 07:30