2015-04-22 84 views
-1

我一直在寻找一种在运行时添加数据源的方法。我想远离在@Configuration类中定义数据源,而是在应用程序加载时我想动态创建数据源bean并将它们注入到Spring上下文中。我真的不知道我该怎么做。Spring 4以编程方式创建Bean

+0

你读过这个问题吗? [http://stackoverflow.com/questions/15328904/dynamically-declare-beans-at-runtime-in-spring](http://stackoverflow.com/questions/15328904/dynamically-declare-beans-at-runtime-春天) – Lukino

+0

我做了,我也看到了其他的例子。在Spring 4.x中,我开始使用spring,我正在寻找新的方式或最佳实践方式。 –

+0

我发布了一个答案,让我知道你的想法。 –

回答

0

这是我结束了,不知道这是否正确的方法,如果有更好的方式,请分享。

@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); 
    }; 
} 

这是我想要做一个例子,但我想最终要动态地创建豆类并将其添加到他们去春来,而不是写出来的配置文件的能力。