Spring 4 以编程方式创建 Bean

Spring 4 Create Bean Programmatically

我一直在寻找一种在运行时添加数据源的方法。我不想在 @Configuration class 中定义数据源,而是在应用程序加载时动态创建数据源 bean 并将它们注入到 Spring 上下文中。我不太确定我该怎么做。

这就是我最后的结果,不确定这是否是正确的方法,如果有更好的方法请分享。

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

这是我想做的事情的一个例子,但我希望最终能够动态创建 bean 并将它们添加到 spring 而不是写出配置文件。