rest - 服务中的 Grails 消息源错误
问题描述
我在 Grails 3.3.11 中遇到了一点问题,我需要帮助。
我正在 grails 3.3.11 中开发一个 rest-api,但我不能在服务中使用 i18n 的消息源。它只适用于我的控制器。
message = messageSource.getMessage('documentProperties.notFound', [partId,jsonRequestDoc.get("typeId")] as Object[], LocaleContextHolder.locale)
当我在上面这样做时,我会在服务中收到它。
Cannot invoke method getMessage() on null object
我的 messageSource 在我的服务类的开头定义如下:
@Autowired
def messageSource
为了解决这个问题,我手动创建了一个从控制器接收消息源的服务构造函数。
class CmbIdService {
public CmbIdService(def messageSource){
this.messageSource = messageSource
}
}
It was working as expected, but when I started running my integration tests, I noticed that Grails did not know how to instantiate my service considering the presence of the constructor. This the message I receive when I run the Grails Integration tests.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cmbIdService': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'java.lang.Object' available: more than one 'primary' bean found among candidates... continue.
任何人都可以帮助我。我不知道该怎么办。我需要使用消息源进行国际化。我需要在服务中做到这一点,而不仅仅是在控制器中。我的测试需要继续工作。
谢谢!
阿尔弗雷多
解决方案
而不是这个...
class CmbIdService {
public CmbIdService(def messageSource){
this.messageSource = messageSource
}
}
做这个...
class CmbIdService {
def messageSource
}
如果该类在 中定义grails-app/services/[whatever your package is]/CmbIdService.groovy
,那么将自动为您创建一个实例,将其作为 bean 添加到应用程序上下文中,并且该实例将受到 autowire-by-name 的约束。
编辑
下面的评论表明 OP 仍在获得 NPE。我在https://github.com/jeffbrown/dnunesmessagesource提供了一个工作示例。
package dnunesmessagesource
import org.springframework.context.i18n.LocaleContextHolder
class CmbIdService {
def messageSource
String getCustomMessage() {
messageSource.getMessage('my.custom.message', [] as Object[], LocaleContextHolder.locale)
}
}
package dnunesmessagesource
class DemoController {
CmbIdService cmbIdService
def index() {
String message = cmbIdService.customMessage
[customMessage: message]
}
}
my.custom.message=This Is My Custom Message
model {
String customMessage
}
json {
message customMessage
}
这一切似乎都按设计工作。
$ http :8080/demo
HTTP/1.1 200
Content-Language: en-US
Content-Type: application/json;charset=UTF-8
Date: Wed, 31 Mar 2021 18:31:37 GMT
Transfer-Encoding: chunked
X-Application-Context: application:development
{
"message": "This Is My Custom Message"
}
推荐阅读
- python - 如何在链表中的另一个节点之间插入一个节点?
- php - PHP 会话计时器最初工作但出错了
- google-cloud-dataflow - 由于设备上没有剩余空间,作业无法完成排空
- haskell - 找不到模块“Text.Parsec.Number”
- java - 有什么方法可以监控指定的 AWS 服务健康状态,例如 SES?
- scala - 无法将 futures-util 板条箱与 Actix 一起使用,因为未实现特征 Future
- swift - 我在 void 函数错误中有一个 Unexpected non-void return value?
- php - API 新手 - PHP 卷曲调用
- scala - 沉降片类有大量物体吗?
- php - 警告:为嵌入的 foreach() HTML 提供的参数无效