I have an app that has a number of datasource settings listed in application.properties. I have a @ConfigurationProperties
class that loads up these settings. Now I want to take the values from this ConfigurationProperties
class and use them to create DataSource beans on-the-fly. I've tried using @PostConstruct
and implementing BeanFactoryPostProcessor
. However, with BeanFactoryPostProcessor
, the processing seems to happen to early - before my ConfigurationProperties
class has been populated. How can I read properties and create DataSource
beans on the fly with Spring Boot?
Here's what my application.properties looks like:
ds.clients[0]=client1|jdbc:db2://server/client1
ds.clients[1]=client2,client3|jdbc:db2://server/client2
ds.clients[2]=client4|jdbc:db2://server/client4
ds.clients[3]=client5|jdbc:db2://server/client5
And my ConfigurationProperties class:
@Component
@ConfigurationProperties(prefix = "ds")
public class DataSourceSettings {
public static Map<String, String> CLIENT_DATASOURCES = new LinkedHashMap<>();
private List<String> clients = new ArrayList<>();
public List<String> getClients() {
return clients;
}
public void setClients(List<String> clients) {
this.clients = clients;
}
@PostConstruct
public void configure() {
for (String client : clients) {
// extract client name
String[] parts = client.split("\|");
String clientName = parts[0];
String url = parts[1];
// client to datasource mapping
String dsName = url.substring(url.lastIndexOf("/") + 1);
if (clientName.contains(",")) {
// multiple clients with same datasource
String[] clientList = clientName.split(",");
for (String c : clientList) {
CLIENT_DATASOURCES.put(c, dsName);
}
} else {
CLIENT_DATASOURCES.put(clientName, dsName);
}
}
}
At the end of this @PostConstruct
method, I'd like to create a BasicDataSource
with these settings and add it to the ApplicationContext. However, if I try to do this by implement BeanFactoryPostProcessor
and implementing postProcessBeanFactory
, the clients
property is null, as is the CLIENT_DATASOURCES
that I've populated with @PostConstruct
.
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("clients: " + CLIENT_DATASOURCES);
}
What's the best way to create datasources on-the-fly with Spring Boot?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…