【问题标题】:Spring 4 Create Bean ProgrammaticallySpring 4 以编程方式创建 Bean
【发布时间】:2015-04-23 03:41:46
【问题描述】:

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

【问题讨论】:

标签: spring-4


【解决方案1】:

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

    @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 而不是写出配置文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    相关资源
    最近更新 更多