Grails提供了 grails.spring.BeanBuilder 类使用动态Groovy来创建bean的声明.
基本点如下:import org.apache.commons.dbcp.BasicDataSource
import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean;
import org.springframework.context.ApplicationContext;
def bb = new grails.spring.BeanBuilder()
bb.beans {
dataSource(BasicDataSource) {
driverClassName = "org.hsqldb.jdbcDriver"
url = "jdbc:hsqldb:mem:grailsDB"
username = "sa"
password = ""
}
sessionFactory(ConfigurableLocalSessionFactoryBean) {
dataSource = dataSource
hibernateProperties = [ "hibernate.hbm2ddl.auto":"create-drop",
"hibernate.show_sql":true ]
}
}
ApplicationContext appContext = bb.createApplicationContext()
在 插件 和 grails-app/conf/spring/resources.groovy 文件中你不需要创建一个BeanBuilder实例, 它在 doWithSpring 和 beans块中都隐式存在.
上面这个例子说明了如果使用 BeanBuilder类来配置某个特定的Hibernate数据源。
实际上,每个方法调用( dataSource 和 sessionFactory 调用) 都映射到Spring中的bean的名字.
方法的第一个参数是bean的class名字, 最后一个参数是一个块(block).
在块内部可以用标准的Groovy语法设置bean的属性。
通过bean的名字自动查找bean的引用. 通过上面的sessionFactory bean解析dataSource可以看点这一点。
也可以通过builder设置一些与bean管理相关的特殊的bean属性,如:sessionFactory(ConfigurableLocalSessionFactoryBean) { bean ->
bean.autowire = 'byName' // Autowiring behaviour. The other option is 'byType'. [autowire]
bean.initMethod = 'init' // Sets the initialisation method to 'init'. [init-method]
bean.destroyMethod = 'destroy' // Sets the destruction method to 'destroy'. [destroy-method]
bean.scope = 'request' // Sets the scope of the bean. [scope]
dataSource = dataSource
hibernateProperties = [ "hibernate.hbm2ddl.auto":"create-drop",
"hibernate.show_sql":true ]
}
括号中的字符串对应于Spring XML定义中相应的bean 属性名。