3

我在 Config.groovy 中定义了一个变量,如下所示

environments {
    development {
        training.defaultStartTime = "09:00"

    }
    production {
        training.defaultStartTime = "09:00"
    }
}

现在我想使用 grailsApplication.config .defaultStartTime 在我的域类中初始化变量 startTime。我正在做如下

class Training {
    def grailsApplication
    String startTime = grailsApplication.config.training.defaultStartTime
}

但是出现错误

“由 BeanCreationException 引起:创建名为 'sessionFactory' 的 bean 时出错:调用 init 方法失败;嵌套异常是 org.hibernate.InstantiationException:无法实例化测试对象 com.Training”

使用config.groovy(grailsapplication)中定义的属性初始化域类变量的最佳方法是什么

4

1 回答 1

4

问题在于注入的工作方式。bean(如果是域类实例)是使用其默认构造函数创建的,然后将 DI 字段设置为相应的 bean。但是该startTime字段是在构造函数中初始化的——在 DI 发生之前——所以grailsApplication是 null。

一种解决方法是创建一个自定义构造函数 -有关详细信息,请参阅http://burtbeckwith.com/blog/?p=1003

于 2012-07-25T08:41:40.407 回答