【问题标题】:Binding bean with dataSource将 bean 与数据源绑定
【发布时间】:2016-03-12 00:48:07
【问题描述】:

在我的ExampleService 中,我尝试使用dataSource_other 获取bean(我必​​须使用多个数据库):

class ExampleService {
    def grailsApplication
    def connectAndCheck(){
        def sourceDatabase = grailsApplication.mainContext.getBean('dataSource_other')
    }
}

在我的 DataSource.groovy 中:

environments {
    production {
        dataSource_information_schema {
            ipDbServer = "1.2.3.4"
            db = "information_schema"
            username = "user"
            password = 'pass'
            pooled = true
            driverClassName = "com.mysql.jdbc.Driver"
            dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
            url = "jdbc:mysql://${ipDbServer}/${db}?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true"
            readOnly = true
        }

        dataSource_other {
            ipDbServer = "1.2.3.5"
            db = "other"
            username = "user2"
            password = 'pass2'
            pooled = true
            driverClassName = "com.mysql.jdbc.Driver"
            dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
            url = "jdbc:mysql://${ipDbServer}/${db}?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true"
        }

很遗憾,我遇到了一个错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 定义了名为“dataSource_other”的 bean

它在我从Config 文件中读取数据源属性的开发环境中工作正常,为什么它不能在生产环境中使用?如何正确制作?

【问题讨论】:

    标签: spring grails datasource


    【解决方案1】:

    你可以这样使用:

    import org.grails.datastore.mapping.core.Datastore
    
    grailsApplication.mainContext.getBeansOfType(Datastore).values().each { d ->
        println d
    }
    

    查看打印语句并找出数据源的 bean。

    【讨论】:

    • 它只包含 1 个数据源,但我在 url 中硬编码 IP 和数据库的名称(而不是在 URL 中使用 GStrings),它也开始在生产中工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2011-10-21
    • 2014-04-04
    • 1970-01-01
    相关资源
    最近更新 更多