I've been looking for a way to add datasources at runtime. I want to move away from defining the datasources in @Configuration class and instead when the app loads i want to dynamically create the datasource beans and inject them into the Spring context. I'm not really sure how I can go about doing that.
Asked
Active
Viewed 956 times
-1
-
Did you read this question ? [http://stackoverflow.com/questions/15328904/dynamically-declare-beans-at-runtime-in-spring](http://stackoverflow.com/questions/15328904/dynamically-declare-beans-at-runtime-in-spring) – Lukino Apr 22 '15 at 18:54
-
I did, and I also seen other examples as well. I started using spring when it was Spring 4.x, i'm looking for the new way or the best practice way. – Hatem Jaber Apr 22 '15 at 19:38
-
I posted an answer, let me know what you think. – Hatem Jaber Apr 22 '15 at 19:42
1 Answers
0
This is what I ended up with, not sure if this is the right approach or not, if there is a better way please share.
@Component
class SpringContextListener implements ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent event) {
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://MySQL:3306/test?useUnicode=true&characterEncoding=utf8&maxAllowedPacket=512000");
ds.setUsername("MYUSERNAME");
ds.setPassword("MYPASSWORD");
ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) event.getApplicationContext();
ConfigurableListableBeanFactory bf = ctx.getBeanFactory();
bf.registerSingleton("mysqlDSN", ds);
};
}
This is an example of what I want to do, but I would like to eventually have the ability to dynamically create beans and add them to them to spring rather than writing out config files.

Hatem Jaber
- 2,341
- 2
- 22
- 38