user2761431
user2761431

Reputation: 975

Configure DataSourceBuilder url dynamically in Spring boot

I have the following properties defined in application.properties file.

sample.db.serverName=10.10.10.10
sample.db.serverPort=1234
sample.db.databaseName=sampleDb

Now I use the DataSourceBuilder, but I need to build the url with all the available information since it has only url parameter.

I am not sure how to read the properties into a POJO and get the handle in the DataSource class

public DataSource dataSource()
{
   //handle for POJO
   //StringBuilder to build the url
   return DataSourceBuilder.create.url(str.toString()).build();
}

P.S : I referred this link, but it is different from my issue.

Upvotes: 0

Views: 2786

Answers (2)

Alex Savitsky
Alex Savitsky

Reputation: 2371

Annotate your method with @Bean, and pass the properties to it using @Value annotation:

@Value("${sample.db.serverName}") private String serverName;
// .. repeat for other properties ...
@Bean public DataSource dataSource() {
    String url = // build URL from serverName field and other fields
    // create DataSource instance and return it
}

You can also use @Value annotation with method parameters, not just fields - but then it starts to look complicated if you call your dataSource() method from code.

Upvotes: 0

Mykola Yashchenko
Mykola Yashchenko

Reputation: 5361

You can create configuration properties class (simple POJO):

@ConfigurationProperties(prefix = "sample.db")
public class DbProperties {
    private String serverName;
    private String serverPort;
    private String databaseName;

    // getters and setters
}

After that you can tell Spring to create an instance of this class and fill properties from the properties file:

@EnableConfigurationProperties(value = DbProperties.class)

And finally you can autowire them into the method which creates datasource:

@Configuration
@EnableConfigurationProperties(value = DbProperties.class)
public class DatasourceConfig {

    @Bean
    public DataSource dataSource(final DbProperties properties) {
        // do whatever you need
        return DataSourceBuilder.create.url(str.toString()).build();
    }
}

Upvotes: 1

Related Questions