CRITICAL UPDATE
我能夠得到您正在尋找的東西。鋪設下來,分步:
需要量 -
當Helper
類被修改,service
類應該被刷新指修改後的輔助類。
SETUP
//src/groovy
class SampleHelper {
String name = 'Heisenberg'
def sayMyName(){
"$name"
}
}
//grails-app/service
import javax.annotation.PostConstruct
class SampleService {
String cachedName
@PostConstruct
def initIt(){
cachedName = new SampleHelper().sayMyName()
}
def serviceMethod() {
cachedName
}
}
//controller
class SampleController {
def sampleService
def index() {
render sampleService.serviceMethod()
}
}
問題描述
當輔助類name
更新爲Gus
,類刷新,但服務類仍引用到的SampleHelper
舊實例。結果,名稱仍顯示爲Heisenberg
。
SOLUTION
- 觀看輔助類。
- 刷新輔助類的服務類
onChange
。
這可以通過在應用程序中使用Pluginator plugin來實現,該應用程序可以靈活地觀看文件並執行某些事件。
- 安裝插件。
- 根據
grails-app/conf
添加以下ApplicationPlugin.groovy
。上述步驟後,接着
作爲
class ApplicationPlugin {
//Watch the helper class
def watchedResources = "file:./src/groovy/**/*.groovy"
//Re-Register the bean (service class) onChange of Helper Class
//This can be generalized more.
def onChange = { event ->
if (event.source) {
def beans = beans {
sampleService(SampleService) { bean ->
bean.autowire = true
}
}
if (event.ctx) {
event.ctx.registerBeanDefinition(
"sampleService",
beans.getBeanDefinition("sampleService"))
}
}
}
}
注意
OLD&有效的答案
我無法重新創建的Grails 2.2.0您的問題。下面是設置我(糾正我,如果我錯了,任何地方):
//src/groovy
class MyHelper{
def sayMyName(){
"Heisenberg"
}
}
//service
import javax.annotation.PostConstruct
class MyService {
def myHelper
@PostConstruct
def initIt(){
myHelper = new MyHelper()
}
def serviceMethod() {
myHelper.sayMyName()
}
}
//controller (to test)
class MyController {
def myService
def index() {
render myService.serviceMethod()
}
}
步驟:
- 運行的初始設置。(
run-app
)
- 命中控制器看到「海森堡」
- 修改
MyHelper.sayMyName()
返回「沃爾特·白」,而不是「海森堡」
- 再次命中控制器,並參閱「沃爾特·白」
觀察:
- 我寧願
MyHelper
一個bean和使用(注),它在使用的服務類。
進入到resources.groovy
如下:
beans = {
myHelper(com.example.MyHelper)
}
服務類變爲:
class MyService {
def myHelper
def serviceMethod() {
myHelper.sayMyName()
}
}
- 現在,在服務類指的領域
MyHelper
會給一個問題,因爲豆已經在容器中實例化了
關於獎金問題:
我無法重現問題無論是在Grails的2.2.0
//domain
class MyDomain {
String name
}
//controller action
def add(){
def myDomain = new MyDomain(name: 'Testing').save(flush: true)
render myDomain.properties
}
- 更改域名,添加
String email
- 保存域類。
- 修改操作在
MyDomain
中添加email
(顯然會創建一個新行)。
- 保存控制器。
- 再次進行操作。
- 查看結果。
爲您的問題找到了解決辦法,請參閱下面「我的答案」中的「CRITICAL UPDATE」。 :) – dmahapatro