0

I need to create a DataSource at runtime. I want to have default properties like Hikaru connection properties and upon that be able to specify username, password, driver and url when creating the DataSource bean.

That's what I'm trying now:

@Configuration
public class DataSourceFactory{

    @Bean(autowireCandidate = false)
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource createDataSource(Properties properties) {
        DataSource dataSource = DataSourceBuilder
                .create()
                .url(properties.getUrl())
                .driverClassName(properties.getDriverClassName())
                .username(properties.getUsername())
                .password(properties.getPassword())
                .build();
        return dataSource;
    }
}

And I'd like to use it like that:

@Component
public class A {
    @Autowire
    DataSourceFactory dataSourceFactory;

    void newDatasource(Properties properties) {
        dataSourceFactory.createDataSource(properties);
        // do sth else here
    }
}

Unfortunately this gives me an error:

Parameter 0 of method createDataSource in DataSourceFactory required a bean of type Properties that could not be found.

I think autowireCandidate = false should deal with that but unfortunately not. Any ideas?

standy
  • 398
  • 1
  • 3
  • 16
  • 1
    Can you please tell me why you want to create it at runtime and where the properties at runtime will come – Simon Martinelli Mar 17 '21 at 17:56
  • I'm creating a separate module which should provide database connectivity functionalities and possibility to specify multiple data sources. Then application using this module should be able to specify list of datasources in it's application.yml which it needs. – standy Mar 17 '21 at 18:06
  • You might want to learn about [JNDI](https://en.wikipedia.org/wiki/Java_Naming_and_Directory_Interface), and LDAP or other naming servers. – Basil Bourque Mar 17 '21 at 19:01
  • @BasilBourque please provide an example of how I could use that in this scenario. Anyway I figured it out myself by adding default dummy bean of Properties class. I think it's a problem on Spring side that it tries to enter the createDataSource method even though it's marked with `autowireCandidate = false` – standy Mar 18 '21 at 12:31

0 Answers0